myol
myol

Reputation: 9828

Inheritence using both the parent attribute and overriden child attribute

I am using inheritance. In one of my methods I would like to use both the parent attribute and the over-riden child attribute together. Something like;

class Parent(object):
    att = 'parent'

    def my_meth(self):
        return super().att + self.att

class Child(Parent):
    att = 'child'

print(Child().my_meth())

Which would print;

parentchild

However the above code gives the error;

'super' object has no attribute 'options'

Is this possible?

Upvotes: 2

Views: 59

Answers (2)

b-fg
b-fg

Reputation: 4137

A way I can think of accessing a static attribute of the parent class that gets overridden by the child is to directly refer to the parent class itself in the method:

class Parent(object):
    att = 'parent'

    def my_meth(self):
        return Parent.att + self.att

class Child(Parent):
    att = 'child'

print(Child().my_meth()) # parentchild

Upvotes: 2

Amit Nanaware
Amit Nanaware

Reputation: 3346

As per the python document the super keyword Return a proxy object that delegates method calls to a parent or sibling class of type. You can not use this for member variables.

Upvotes: 1

Related Questions