Skip to main content

Command Palette

Search for a command to run...

shadowing class attributes

Published
2 min readView as Markdown
shadowing class attributes
X

"I am currently a Software Engineering student at ALX. I'm passionate about technology and enjoy conducting research to find answers on my own. I have a natural inclination to ask 'WHY' more often than 'HOW'.

"While working on projects at ALX, I have acquired a wealth of interesting and diverse knowledge about software engineering and computer science in general. Therefore, I needed a place to store and save all this information, allowing me to refer back to it whenever I forget."

what will this print

>>> class User: 
...    id = 1 

>>> u = User() 
>>> u.id = 89 
>>> User.id = 98 
>>> print(u.id)
89

This code will print the value 89.

Here's a step-by-step breakdown of what happens:

  1. The User class is defined with a class attribute id initialized to 1.

  2. An instance of the User class is created and assigned to the variable u.

  3. The instance u is modified by assigning the value 89 to its id attribute. This creates an instance attribute id for u that shadows the class attribute.

  4. The class attribute id is modified by assigning the value 98 to it.

  5. When print(u.id) is called, it accesses the instance attribute id of u, which has the value 89. Hence, the output will be 89.

In Python, you can access the class attribute id with an instance u of the User class using dot notation (u.id). However, if the instance has its own attribute with the same name, it will shadow the class attribute, and the value of the instance attribute will be retrieved instead.

In the code snippet you above, you assign a value of 89 to u.id, which creates an instance attribute that shadows the class attribute id. When you print u.id, it retrieves the value of the instance attribute, which is 89.

If you must access the class id using the class instances:

If you specifically want to access the class attribute id using the instance u (rather than directly using the class name), you can use the __class__ attribute of the instance. Here's an example:

class User:
    id = 1

u = User()
u.id = 89
User.id = 98

print(u.__class__.id)  # Output: 98

More from this blog

PERSONAL BLOG

110 posts

Use the search button to search for a specific topic or keyword *all posts are updated on the go*