具有抽象方法和属性的继承

2024-07-02 14:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

继承类是否可能调用引用子类的父抽象方法,而不事先知道子类

class AbsParent(object):
    att = 'parent'

    def my_meth():
        return AbsParent.att

class AbsChild(AbsParent):
    att = 'child'

print(AbsChild.my_meth())

显然,上面的代码将始终返回parent,因为父类通过AbsParenet.att调用自己的属性

子类是否有一种干净的方法可以使用继承的父类方法,但仍然引用自己的属性来打印child?我只能想到这样可怕的事情

 class AbsParent(object):
     att = 'parent'

     def my_meth(abs_class):
          return abs_class.att

 class AbsChild(AbsParent):
    att = 'child'

print(AbsChild.my_meth(AbsChild))

Tags: 方法childreturnobjectmydef子类att
1条回答
网友
1楼 · 发布于 2024-07-02 14:01:47

现在还不太清楚是否将my_meth定义为类方法。您正在使用类AbsChild进行调用,因此可能需要类似以下内容:

class AbsParent(object):
    att = 'parent'
    @classmethod
    def my_meth(cls):
        return cls.att

class AbsChild(AbsParent):
    att = 'child'

print(AbsChild.my_meth())

或者,对于实例方法:

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

两者都打印child

相关问题 更多 >