Reputation: 341
I wrote Class and created two lists. The first for the users and the second for the user-attributes.
I would now like to loop trough the two lists in order to create multiple Class instances with the respective data.
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
emp_1 = Employee('Corey', 'Schafer', '50000')
emp_2 = Employee('Test', 'User', '60000')
by printing print(amp_1.email)
i can create the instance of the class:
will print
[email protected]
Now i dont want to write it out manually so i want to loop trough it:
for user in users:
for user_atr in user_atrs:
print(user + '.' + user_atr)
will print:
empy_1.first
empy_1.last
empy_1.pay
empy_1.email
empy_2.first
empy_2.last
empy_2.pay
empy_2.email
Instead of:
Corey
Schafer
50000
[email protected]
Test
User
60000
[email protected]
How can i use that loop to actually create the instance of the class and not just the blueprint?
Upvotes: 1
Views: 253
Reputation: 54148
string
of the users : ['emp_1', 'emp_2']
string
that are attributs name ['first', 'last', 'pay', 'email']
Then use the builtin method globals()
to get the variable and getattr(obj, name, default)
but that isn't nice and requires to type variable names
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', '60000')
for user in ['emp_1', 'emp_2']:
for user_atr in ['first', 'last', 'pay', 'email']:
print(getattr(globals()[user], user_atr))
Employee
instances : [emp_1, emp_2]
__dict__
(key
is name, value
are property's value)for user in [emp_1, emp_2]:
for user_atr in user.__dict__.values():
print(user_atr)
Corey
Schafer
50000
[email protected]
...
To read both name and value at the same time
for user in [emp_1, emp_2]:
for user_atr in user.__dict__.items():
print(user_atr)
('first', 'Corey')
('last', 'Schafer')
('pay', 50000)
('email', '[email protected]')
...
Upvotes: 3
Reputation: 446
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
emp_1 = Employee('Corey', 'Schafer', '50000')
emp_2 = Employee('Test', 'User', '60000')
users = {"emp_1": emp_1,
"emp_2": emp_2}
for user in users.values():
for attribute in list(user.__dict__.keys()):
print(f"{name}.{attribute}")
This will do that for you by storing the users in a dictionary with the name of the user as the dictionary key and then using the __dict__
attribute from the Employee
class to get a dictionary of all atributes and then printing the name of each attribute from that dictionary.
If you are trying to print the value of each of these attributes then it can be changed to the following:
users = {"emp_1": emp_1,
"emp_2": emp_2}
for name, user in users.items():
for attribute in list(user.__dict__.keys()):
print(getattr(user,attribute))
Using this method means that any more attributes added to the employee class will be printed also.
Upvotes: 1