2

Say I want to implement a simple database in Python. I do this by creating a class

class myStruct():
    def __init__(self,name,salary,doB,title):
        self.name=name
        self.salary=salary
        self.doB=doB
        self.title=title

Now, I want to create objects of that class. But I want users to input all the variables themselves for each object, and the name of the object would be the user inputted name. I saw some other StackOverflow pages describing something like this, such as this link how to dynamically create an instance of a class in python? but that had to do with a classes imported from another module, and I didn't understand klass=global()["class_name"]. I don't understand how to link from user inputted string to use global().

Again, the idea is even the name of every object of class myStruct is typed in by the user, along with all the other fields for that object. How would I do this?

EDIT: I don't think some people understood what I was trying to do. The point is not to write out

instance=MyStruct(name,salary,doB,title)

in my code but instead, to have a function that creates an instance that's named after whatever user inputted for name. so it would be something like

name=input('Enter your name') 
'%s' %name=MyStruct(name) 

Do you get it? The name is substituted in.

Nicholas A. Randall
  • 421
  • 1
  • 5
  • 13

4 Answers4

3
# Collect the data from user
nameVar = input('Type the name: ')
salVar = input('Type the salary: ')
dobVar = input('Type the doB: ')
titleVar = input('Type the title: ')

# Create the instance of the myStruct object
myInstance = myStruct(nameVar, salVar, dobVar, titleVar)

By the way, is bad style naming a class without capitalizing. You should always call your classes with the first letter in uppercase => MyStruct

madtyn
  • 1,469
  • 27
  • 55
2

You coculd:

  1. Just use that myStruct and create an object after asking for parameters, like this:

    class myStruct():
        def __init__(self, name, salary, doB, title):
            self.name = name
            self.salary = salary
            self.doB = doB
            self.title = title
    
    name = raw_input('Enter name: ')
    salary = raw_input('Enter salary: ')
    doB = raw_input('Enter doB: ')
    title = raw_input('Enter title: ')
    
    new_object = myStruct(name, salary, dob, title)
    
  2. Or, you could tweak __init__ a bit to do what you need. It may not be neat but it will work.

    class myStruct():
        def __init__(self,name=None,salary=None,doB=None,title=None):
            if not name:
                self.name = raw_input('Enter name: ')
            else:
                self.name=name
            if not salary:
                self.salary = raw_input('Enter salary: ')
            else:
                self.salary=salary
            if not soB:
                self.doB = raw_input('Enter doB: ')
            else:
                self.doB=doB
            if not title:
                self.title = raw_input('Enter title: ')
            else:
                self.title=title
    
joegalaxian
  • 350
  • 1
  • 7
0

I was running into a similar problem ... But in my case, my input "names" are from a file and the number of attributes can vary. The following is my current solution. I'm sure there are better ways to do this, and I hope someone else can provide those.

import numpy as np

class Target():
    sample = {}
    @classmethod
    def create(cls, name):
        target = Target(name)
        cls.sample[name] = target
        return target
    def __init__(self, name):
        self.name = name


names = ('Moon', 'Earth', 'Mars')
# gravity in units of m / s^{-2}
grav = np.array([1.620, 9.807, 3.711])
sample = {}
for idx in np.arange(0, len(names), 1):
    name = names[idx]
    sample[name] = Target(name)
    setattr(sample[name], 'grav', grav[idx])
    if (name == names[1]):
        # number of moons
        setattr(sample[name], 'num_moons', 1)
    elif (name == names[2]):
        # number of moons
        setattr(sample[name], 'num_moons', 2)

for idx in np.arange(0, len(names), 1):
    name = names[idx]
    print(sample[names[idx]].name + ':')
    print('    Gravity = %.3f (m s^{-2})'%sample[names[idx]].grav)
    if (idx == 1):
        print('    Number of moons = %i'%(sample[names[idx]].num_moons))

P.S. You can imagine that my input file has three lines, and each line has different length (but not difficult to convert into lists, numpy arrays). Moon 1.620 Earth 9.807 1 Mars 3.711 2

0

Try to input strings from outside the class by passing it in to init as normal using two ways : input() or raw_input().

The fucntion named output_all is used to print saved data.

class myStruct():
        def __init__(self,name,salary,doB,title):
            self.name=name
            self.salary=salary
            self.doB=doB
            self.title=title
        def output_all(self):
            print( '{} \n{} \n{} \n{}'.format(self.name,self.salary, self.doB, 
            self.title))

    user = myStruct(
        name = input('type your name: '),
        salary = input('type your salary : '),
        doB = input('type your doB: '),
        title = input('type you title : ') 
        )

    myStruct.output_all(user)