piny
piny

Reputation: 153

Why doesn't the super function work to get class attributes?

From what I've read, the super function is used to refer to the parent class. But if so, how come this doesn't work?

class Parent:
    x = 5

class Child(Parent):
    x = super().x + 3

obj = Child()
print(obj.x)

Upvotes: 1

Views: 74

Answers (2)

flakes
flakes

Reputation: 23684

As mentioned, super() without args will only work in an instance method. If you really need it to work without referencing the parent twice, then I would make x a @property instead. That way you can access it from an instance context:

class Parent:
    x = 5

class Child(Parent):
    @property
    def x(self):
        return super().x + 3


obj = Child()
print(obj.x)

Upvotes: 1

Gab
Gab

Reputation: 3520

This is how you would do it:

class Parent:
    x = 5

class Child(Parent):
    x = Parent.x + 3

obj = Child()
print(obj.x)

->

8

super() does not exactly do that, the super() function is used to give access to methods and properties of a parent or sibling class. You can read more about super() here.

Upvotes: 0

Related Questions