About attributes in classes

Hello There;
how can i get the “id” of user_01 after creating user_02 ?

class User:
    def __init__(self,user_id):
        User.id = user_id

user_01 = User("001")
user_02 = User("002")


that gives me “002” instead of “001”
Please help

In your class you’ve assigned data to “User.id”. As User is the class, this becomes a class attribute. There’s only one variable for the whole class, but the instances can see it. When the second instance is created, the class attribute is overwritten and only “002” is kept. You want to have an instance attribute instead (one for each instance).

Change the assignment to read:

self.id = user.id

Self refers to the created instance, not to the entire class.

1 Like

In your constructor, you have this:

User.id = user_id

This attaches the user_id to the class object, so it is shared by all
instances. If you want every instance to get its own ID attribute, you
have to write it to the instance:

self.id = user_id
1 Like

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

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

Now change the init method to set “self.id” instead, and see the
difference in the print statements.

Cameron Simpson cs@cskk.id.au

1 Like

thank you all. i really appreciate your help