Python:在父类方法中调用类方法,但绑定到子类
假设我有以下代码:
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 中重写的属性。有没有什么好办法可以做到这一点呢?
3 个回答
0
你真的需要把 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'
1
这里有一个选择:
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
0
这个应该可以用:
Parent.foo.im_func(Child)
不过看起来有点不太好。