仅当基类在 Python 中没有子类时才调用基类
我需要编写一个基类(在本例中为 A 类),该基类可能(但并非总是)被子类化。我只想在基类未子类化时才从基类调用“Run”方法,否则仅从子类调用“Run”方法。
这就是我所拥有的,它似乎有效,但我想知道是否有更简单或更Pythonic 的方法。
class A(object):
def __init__(self):
pass
def Run(self):
print "Calling A.Run()"
class B(A):
def __init__(self):
A.__init__(self)
pass
def Run(self):
print "Calling B.Run()"
subs = A.__subclasses__()
if subs: inst = [i() for i in subs]
else: inst = [A()]
[each.Run() for each in inst]
I need to write a base class (in this example, class A) that will likely, but not always, be subclassed. I want to call the 'Run' method from the base class only if its not subclassed, else only call the the 'Run' method from the subclasses.
This is what I have, it seems to work but I'm wondering if there is an easier or more Pythonic way.
class A(object):
def __init__(self):
pass
def Run(self):
print "Calling A.Run()"
class B(A):
def __init__(self):
A.__init__(self)
pass
def Run(self):
print "Calling B.Run()"
subs = A.__subclasses__()
if subs: inst = [i() for i in subs]
else: inst = [A()]
[each.Run() for each in inst]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你所拥有的看起来是正确的,除了大多数程序员会查看 B.Run 方法并想:“哦,他忘了调用 super。让我添加一下......”但我相信你会解释你的意思在你的实际实现中正在做:)
如果你担心 C++ 中的切片之类的事情,那么请放心。你拥有的很好。
至于让它变得“更容易”,我不知道除了删除 A 的空
__init__
函数并从 B 的__init__
中删除pass
之外,你还能如何简化它代码>.What you have looks correct, except that most programmers would look at the B.Run method and think: "Oh, he forgot to call super. Let me just add that..." but I'm sure you'd explain what you're doing in your real implementation :)
If you're worried about something like slicing in C++, then be reassured. What you have is good.
As for making it "easier", I'm not sure how you could simplify it aside from removing A's empty
__init__
function and removingpass
from B's__init__
.这是默认发生的情况,调用最具体的方法。
如果您确实不希望子类可以使用基方法,您可以编写如下内容:
This is what happens by default, the most specific method is called.
If you really don't want the base method to be available from subclasses, you can write something like this: