仅当基类在 Python 中没有子类时才调用基类

发布于 2024-11-15 08:24:07 字数 510 浏览 2 评论 0原文

我需要编写一个基类(在本例中为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城挽邺 2024-11-22 08:24:07

你所拥有的看起来是正确的,除了大多数程序员会查看 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 removing pass from B's __init__.

桃扇骨 2024-11-22 08:24:07

仅当基类没有子类化时,我才想从基类调用“Run”方法,否则仅从子类调用“Run”方法。

这是默认发生的情况,调用最具体的方法。

如果您确实不希望子类可以使用基方法,您可以编写如下内容:

class C(object):
    def Run(self):
        if self.__class__ != C:
            raise NotImplementedError("You need to override this method")

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 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:

class C(object):
    def Run(self):
        if self.__class__ != C:
            raise NotImplementedError("You need to override this method")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文