简体   繁体   English

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

[英]Check if self is instance of subclass in python

I have a class called A , with two subclasses B and C . 我有一个名为A的类,其中有两个子类BC Does the following make sense? 以下内容有意义吗? Or is there a better way to it? 还是有更好的方法呢?

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()

There's a better way to do it: Override do_stuff in the child classes. 有一种更好的方法:在子类中覆盖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()

The advantage of this solution is that the base class doesn't have to know about its child classes - B and C aren't referenced anywhere in A 's body. 此解决方案的优点是基类不必了解其子类BCA的主体中均未引用。 This makes it easier to add additional subclasses, should that ever be necessary. 如果需要的话,这使得添加其他子类更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM