如何从超类方法调用 python 子类方法?
我有以下类型的超类/子类设置:
class SuperClass(object):
def __init__(self):
self.do_something() # requires the do_something method always be called
def do_something(self):
raise NotImplementedError
class SubClass(SuperClass):
def __init__(self):
super(SuperClass, self).__init__() # this should do_something
def do_something(self):
print "hello"
我希望 SuperClass init 始终调用尚未实现的 do_something 方法。我正在使用 python 2.7。或许ABC可以做到这一点,但是还有别的办法吗?
谢谢。
I have the following kind of superclass / subclass setup:
class SuperClass(object):
def __init__(self):
self.do_something() # requires the do_something method always be called
def do_something(self):
raise NotImplementedError
class SubClass(SuperClass):
def __init__(self):
super(SuperClass, self).__init__() # this should do_something
def do_something(self):
print "hello"
I would like the SuperClass init to always call a not-yet-implemented do_something method. I'm using python 2.7. Perhaps ABC can do this, but it is there another way?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除了使用
super
之外,您的代码大部分都是正确的。您需要将当前类名放入super
调用中,因此:由于您输入了错误的类名,因此未调用
SuperClass.__init__
,并且结果do_something
也没有被调用。Your code is mostly correct, except for the use of
super
. You need to put the current class name in thesuper
call, so it would be:Since you put in the wrong class name,
SuperClass.__init__
wasn't called, and as a resultdo_something
wasn't called either.