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 中被覆盖。有什么想法如何做到这一点?
Say I have the following code:
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()
In Parent.__init__
, I need to call 'foo' that is defined within Parent, but I need to call it bound to Child, so that accessing cls.classattr1 will actually access the attribute as it is overridden in Child. Any ideas how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个选项:
Parent.foo()
不再是类方法,但最终结果应该与您想要的相同。Here is an option:
Parent.foo()
is not a class method anymore, but the end result should be the same as what you want.这应该可行:
但看起来有点邪恶。
This should work:
but looks kinda evil.
您真的需要
foo
成为classmethod
吗?如果没有,这有效:Do you really need
foo
to be aclassmethod
? If not, this works.: