Reputation: 9878
Is it possible for an inherited class to call a parents abstract method which refers to the child class without knowing the child class in advance?
class AbsParent(object):
att = 'parent'
def my_meth():
return AbsParent.att
class AbsChild(AbsParent):
att = 'child'
print(AbsChild.my_meth())
Obviously the code above will always return parent
since the parent class is calling its own attribute via AbsParenet.att
Is there a clean way the child class can use the Parent class method using inheritance but still reference its own attribute to print child
? I can only think of something horrible like this
class AbsParent(object):
att = 'parent'
def my_meth(abs_class):
return abs_class.att
class AbsChild(AbsParent):
att = 'child'
print(AbsChild.my_meth(AbsChild))
Upvotes: 1
Views: 41
Reputation: 92461
It's not super clear whether you indend my_meth
to be a class method or not. You're calling with the class AbsChild
so maybe you want something like:
class AbsParent(object):
att = 'parent'
@classmethod
def my_meth(cls):
return cls.att
class AbsChild(AbsParent):
att = 'child'
print(AbsChild.my_meth())
Alternatively for an instance method:
class AbsParent(object):
att = 'parent'
def my_meth(self):
return self.att
class AbsChild(AbsParent):
att = 'child'
c = AbsChild() # make instance
print(c.my_meth())
both print child
Upvotes: 2