同时使用父属性和重写的子属性的继承

2024-10-04 05:25:08 发布

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

我用的是继承。在我的一个方法中,我想同时使用parent属性和over riden子属性。有点像

class Parent(object):
    att = 'parent'

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

class Child(Parent):
    att = 'child'

print(Child().my_meth())

它会打印出来

parentchild

但是上面的代码给出了错误

'super' object has no attribute 'options'

这可能吗?你知道吗


Tags: 方法selfchild属性objectmydefatt
2条回答

根据pythondocument,super关键字返回一个代理对象,该对象将方法调用委托给类型为的父类或同级类。不能将其用于成员变量。你知道吗

访问被子类重写的父类的静态属性的一种方法是在方法中直接引用父类本身:

class Parent(object):
    att = 'parent'

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

class Child(Parent):
    att = 'child'

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

相关问题 更多 >