Home > Net >  How to create a function that generates instances of a class from its arguments
How to create a function that generates instances of a class from its arguments

Time:06-29

I'm a python newbie, and I'm trying to create a function that returns an instance of one of three classes, using the arguments of the function as attributes of the instance.

class User:
    def __init__(self, nick, full_name, reg_date, age, role):
        self.nick = nick
        self.full_name = full_name 
        self.reg_date = reg_date
        self.age = age
        self.role = role

class Staff(User):
    def __init__(self, nick, full_name, reg_date, age, role):
        super().__init__(nick, full_name, reg_date, age, role)


class Adult(Staff):
    def __init__(self, nick, full_name, reg_date, age, role):
        super().__init__(nick, full_name, reg_date, age, role)

class Young(Adult):
    def __init__(self,nick, full_name, reg_date, age, role):
        super().__init__(full_name, nick, reg_date, age, role)



def sign_up(nick, full_name, reg_date, age, role):
    nick = (input('Choose a nickname: '))
    full_name = (input('Please, introduce your name: '))
    reg_date = str(date.today())
    age = (input('Please, introduce your age: '))
    role = (input('Please, introduce your role (Staff, Adult or Young)'))
    valid_roles = ['Staff', 'Adult', 'Young']
    exec('nick = role(full_name, reg_date, age, role)

My goal is that when you run the sign in function the value the user introduces into "nick" argument will be the instance name, role the class of the instancem, and the other arguments work as the instance.

for example:

sign_in('nick1', 'John Doe', reg_date, 38, 'Staff')

Should result in this:

nick1 = Staff(full_name, reg_date, age)

Is my first question here in Stack Overflow and I hope I explained myself clearly. Thanks.

CodePudding user response:

Don't arbitrarily make variables. Use something like a dictionary instead.

class User:
    def __init__(self, nick, full_name, reg_date, age, role):
        self.nick = nick
        self.full_name = full_name 
        self.reg_date = reg_date
        self.age = age
        self.role = role

class Staff(User):
    pass

class Adult(Staff):
    pass

class Young(Adult):
    pass

def sign_up(nick, full_name, reg_date, age, role):
    user = {}
    if role == 'Staff':
        user[nick] = Staff(nick, full_name, reg_date, age, role)
    elif role == 'Adult':
        user[nick] = Adult(nick, full_name, reg_date, age, role)
    elif role == 'Young':
        user[nick] = Young(nick, full_name, reg_date, age, role)
    return user

users = {}

users |= sign_up('nick1', 'John Doe', 'today', 38, 'Staff')
users |= sign_up('nick2', 'Jane Doe', 'yesterday', 40, 'Adult')
print(users)

Output:

{'nick1': <__main__.Staff object at 0x1009d2c80>,
 'nick2': <__main__.Adult object at 0x100ae1b10>}
  • Related