假设我有以下代码:
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/