That is because you have set the .id attribute of the class “User”, not
of the instance “self”. You want:
def __init__(self,user_id):
self.id = user_id
When you look up an object’s attributes (by going “user_01.id”) it looks
for the attribute first on the object (“user_01”). However, if it does
not have such an attribute, the object’s class is consulted.
Since you set the attribute on the class (which is itself an object like
any other, so you can set attributes on it), and never on the
instances of the class, “.id” is never found on the instances and always
comes from the class.
When you set up user_02, it overwrote the class attribute with “002”. So
both user_01 and user_02 report “002” because they both find it on the
class.
Before you change you code, add this to the bottom of your script:
print("User:", repr(User.__dict__))
print("user_01:", repr(user_01.__dict__))
print("user_02:", repr(user_02.__dict__))
So that there is an ‘id’ on the User object and not on user_01 or
user_02?
Now change the init method to set “self.id” instead, and see the
difference in the print statements.
Cheers,
Cameron Simpson cs@cskk.id.au