【问题标题】:Check if self is instance of subclass in python检查self是否是python中子类的实例
【发布时间】:2018-11-01 15:54:03
【问题描述】:

我有一个名为A 的类,有两个子类BC。以下内容有意义吗?还是有更好的办法?

class A():
    ...

    def do_stuff(self):
        self.do_this()
        self.do_that()
        if isInstance(self, B):
            self.do_the_b_stuff()
        elif isInstance(self, C):
            self.do_the_c_stuff()

【问题讨论】:

    标签: python self isinstance


    【解决方案1】:

    有一个更好的方法:在子类中覆盖 do_stuff

    class A:
        def do_stuff(self):
            self.do_this()
            self.do_that()
    
    class B(A):
        def do_stuff(self):
            super().do_stuff()  # call the parent implementation
            self.do_the_b_stuff()
    
    class C(A):
        def do_stuff(self):
            super().do_stuff()  # call the parent implementation
            self.do_the_c_stuff()
    

    此解决方案的优点是基类不必知道它的子类 - BC 不会在 A 的主体中的任何地方引用。这使得添加额外的子类变得更加容易,如果有必要的话。

    【讨论】:

    • 感谢您的编辑。我很高兴知道为什么这会更好,这很有意义。也谢谢你的回答!
    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 2013-05-17
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多