检查self是否是python中子类的实例

luk*_*awk 2 python self isinstance

我有一个名为的类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()
Run Code Online (Sandbox Code Playgroud)

Ara*_*Fey 6

有一种更好的方法:覆盖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()
Run Code Online (Sandbox Code Playgroud)

这个解决方案的优点是基类不必知道它的子类 - B并且C不会在A体内的任何地方引用.如果有必要,这可以更容易地添加其他子类.