1

Edit: Please note that I used the wrong term "property" here. Instead I used a class variable ("field" in other programming languages).

If I set a class (or static) property of a class via an instance of that class, the property of this instance references the newly set object, but the class or other instances reference the object that was set on the class level:

class ClassPropertyDemo:
    some_value = 42

cpd_1 = ClassPropertyDemo()
cpd_2 = ClassPropertyDemo()

# Set some_value via the second instance
cpd_2.some_value = 21

print(ClassPropertyDemo.some_value)  # 42 - The value of the class property
print(cpd_1.some_value)              # 42 - The value of the class property
print(cpd_2.some_value)              # 21 - The value set to the property of the class instance

My question is what actually happens here. Is cpd_2.some_value a new instance property, dynamically created, that hides the class property?

Jürgen Bayer
  • 2,993
  • 3
  • 26
  • 51
  • 1
    Yes, you create a new instance attribute (a property is something different) like it is done by e. g. `self.some_value = 21` often seen in `__init__`. – Michael Butscher Jun 18 '20 at 15:13
  • 1
    The lookup order is important, but basically it feels like overwriting the class property. Since you are looking up the instance attribute with the same name first, the class attribute is hidden / shaded / shadowed. – Joe Jun 18 '20 at 15:48
  • 1
    @MichaelButscher: Thanks for noting my error. But even "attribute" is not perfectly clear., since an attribute is "any name following a dot" (see https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces). I think that "class variable" is the right term. – Jürgen Bayer Jun 18 '20 at 19:03

1 Answers1

0

You can extend your code to make it even clearer by adding:

del cpd_2.some_value
print(cpd_2.some_value)              # 42 - 'Unhide' the original value 
Ronald
  • 2,930
  • 2
  • 7
  • 18
  • I assume that the actual answer is "Yes, when overwriting class attributes via an instance a new instance attribute is created" and accept this answer :-) – Jürgen Bayer Jun 18 '20 at 16:18