Preface: I've spent many HOURS trying to read similar posts like this one and try lots of different things, but for the life of me, I can't understand what I'm doing wrong, or why this doesn't work. Can someone please give me an ELI5 answer as to either what I'm doing wrong, or why this doesn't work the way I'm expecting?
class User:
def __init__(self, first, last, age):
self.firstname = first
self.lastname = last
self.age = age
dict = {
'User1': {'id': 'id001', 'firstname': 'User', 'lastname': 'One', 'age': 11},
'User2': {'id': 'id002', 'firstname': 'User', 'lastname': 'Two', 'age': 22},
'User3': {'id': 'id003', 'firstname': 'User', 'lastname': 'Three', 'age': 33}
}
for user in dict:
u = dict[user]
user = User(u['firstname'], u['lastname'], u['age'])
try:
print(User1.lastname)
except Exception as e:
print(e)
finally:
print(user.lastname)
Which returns:
name 'User1' is not defined
Three
Clearly user
is getting instantiated three times with the data from dict
, with User3
's data being the last of it.
If I do a:
for user in dict:
print(user)
it prints out:
User1
User2
User3
So my expectation would be that the for loop would run, and then I'd be able to call User1.firstname
, User2.lastname
, or User3.age
, and it'd give me the same data that's in dict
(User, Two, 33, respectively), but that's clearly not the case.
Help?