I've wrote the following code to explain what I've found using super(). :
With Parent.set_prop():
class Parent:
parent_prop = None
@classmethod
def set_prop(cls, value):
cls.parent_prop = value
class Child1(Parent):
@classmethod
def set_prop(cls, value):
print("Child1 set parent prop")
Parent.set_prop(value)
class Child2(Parent):
pass
cls1 = Child1()
cls2 = Child2()
cls1.set_prop(10)
print(cls1.parent_prop)
print(cls2.parent_prop)
With super().set_prop()
class Parent:
parent_prop = None
@classmethod
def set_prop(cls, value):
cls.parent_prop = value
class Child1(Parent):
@classmethod
def set_prop(cls, value):
print("Child1 set parent prop")
super().set_prop(value)
class Child2(Parent):
pass
cls1 = Child1()
cls2 = Child2()
cls1.set_prop(10)
print(cls1.parent_prop)
print(cls2.parent_prop)
The result of the first execution is:
Child1 set parent prop
10
10
The result of the second execution is:
Child1 set parent prop
10
None
I didn't expect any differences between both. Why calling the set_prop method with super() doesn't set the value for all instances of the class?
The difference is obvious when you add a
print(cls)toParent.set_prop:When ran in case 1 :
When ran in case 2 :
That's because
superdoes not give you the parent class, but a proxy which will call the parent's methods (using a special__getitem__) but with the same parameters, here the same value forclswhich isChild1in the second case, but simplyParentin the first case.