Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic objects python

For training, I want to atumaticly create users in a system using class.

Here is my code:

class CsrUser(object):
    def __init__(self, f_name, l_name, login, role, sex, password ='Hot12345'):
        self.f_name = f_name
        self.l_name = l_name
        self.login = login
        self.role = role
        self.sex = sex
        self.password = password

I want to create dynamic objects of the class from the user input,

#i want to create something like this
def get_users_data():
    new_user = input("Enter the user name")
    ... #get all the data
    new_user = CsrUser(...)

I want the name of the object to be the value that inside new_user

like image 807
Or Halimi Avatar asked Oct 28 '25 12:10

Or Halimi


1 Answers

I don't think that naming a variable (object in your case) using a variable is a good idea. If you want to keep track of all of your users by name, you should use a dictionary instead:

#make dictionary
user_data = {}

#make a new user object
new_user = CsrUser(...)

#insert your new user object into the dictionary
#use new_user.f_name or new_user.l_name here in place of new_user.name (or combine both)
user_data[new_user.name] = new_user  

#to get a user object out of the dictionary 
a_user = user_data["name_here"]
like image 105
Tyler Avatar answered Oct 31 '25 01:10

Tyler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!