python:在父类的方法中,调用该类的类方法,但绑定(bind)到子类

标签 python inheritance attributes class-method

假设我有以下代码:

class Parent(object):
    classattr1 = 'parent'
    def __init__(self):
        Parent.foo()

    @classmethod
    def foo(cls):
        print cls.classattr1

class Child(Parent):
    classattr1 = 'child'

    def foo(cls):
        raise Exception("I shouldn't be here")

Child()

Parent.__init__ 中,我需要调用在 Parent 中定义的“foo”,但我需要调用它绑定(bind)到 Child,以便访问 cls.classattr1 实际上将访问该属性它在 Child 中被覆盖。任何想法如何做到这一点?

最佳答案

这里有一个选项:

class Parent(object):
    classattr1 = 'parent'
    def __init__(self):
        Parent.foo(self)

    def foo(self):
        print self.classattr1     # or self.__class__.classattr1

class Child(Parent):
    classattr1 = 'child'
    def foo(cls):
        raise Exception("I shouldn't be here")

Child()

Parent.foo() 不再是类方法,但最终结果应该和你想要的一样。

>>> c = Child()    # prints 'child' by calling Parent.foo()
child
>>> c.foo()        # Child.foo() raises an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in foo
Exception: I shouldn't be here

关于python:在父类的方法中,调用该类的类方法,但绑定(bind)到子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7533120/

相关文章:

c++ - 访问派生类中类的 protected 成员

c# - 从 MethodInfo 创建委托(delegate)

xslt - 使用 XSL 对属性进行排序

Python - 计算相同长度列表中出现次数最多的元素

python - 计算 python 文件中每个类的代码行数?

c++ - 异常多重继承

constructor - 使用私有(private)属性复制构造函数

python - 在 Python 中连接列表和字符串

python - 按特定字母拆分字符串,同时将它们保留在字符串中