假设我有以下代码:
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',但我需要调用它绑定到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
应该可以:
Parent.foo.im_func(Child)
但是看起来有点邪恶
你真的需要foo
成为classmethod
吗?
class Parent(object):
classattr1 = 'parent'
def __init__(self):
Parent.foo(self)
def foo(self):
print self.classattr1
class Child(Parent):
classattr1 = 'child'
def foo(self):
raise AttributeError("Wrong foo!")
Child() # prints 'child'