Jordan Russev
Jordan Russev

Reputation: 77

Difference between super() and {parent_class_name} in case of update class property

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?

Upvotes: -1

Views: 60

Answers (1)

Lenormju
Lenormju

Reputation: 4368

The difference is obvious when you add a print(cls) to Parent.set_prop :

    @classmethod
    def set_prop(cls, value):
        print(cls)
        cls.parent_prop = value

When ran in case 1 :

Child1 set parent prop
<class '__main__.Parent'>
10
10

When ran in case 2 :

Child1 set parent prop
<class '__main__.Child1'>
10
None

That's because super does 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 for cls which is Child1 in the second case, but simply Parent in the first case.

Upvotes: 2

Related Questions