简体   繁体   中英

Inheritence with abstract methods and attributes

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM