【问题标题】:Python: How to use isinstance from parent to determine if it is a specific childPython:如何使用来自父母的 isinstance 来确定它是否是特定的孩子
【发布时间】:2014-12-01 11:25:00
【问题描述】:

我有几节课

class Parent():
    def DoThing():
        if isinstance(self, 'child1'):
            DoSomething()
        elif:
            DoSomethingElse()

import Parent
class Child1(Parent):
    def DoThing():
        #Do some things here
        super.DoThing()

import Parent
class Child2(Parent)
    def DoThing():
        #Do other things
        super.DoThing()

我遇到的问题是我想检查类的实例是父级本身还是子级之一。

失败点是在解释 Parent 时,进程失败,因为解释器不知道 Child1 是什么。我无法导入 Child1,因为这会导致递归。

我通过在 parent 和 child1 中定义一个方法来解决这个问题。

def IsChild1Instance(self):
    return True/False

有没有更好更清洁的方法?

【问题讨论】:

    标签: python inheritance recursion isinstance


    【解决方案1】:

    你的父类不应该关心子类。改为使用方法的不同实现:

    class Parent:
        def do_thing(self):
            self.do_something_delegated()
    
        def do_something_delegated(self):
            pass
    
    class Child1(Parent):
        def do_something_delegated(self):
            # do child1 specific things
    
    class Child2(Parent)
        def do_something_delegated(self):
            # do child2 specific things
    

    【讨论】:

      猜你喜欢
      • 2015-04-07
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 2015-08-30
      • 2020-03-18
      • 2011-01-19
      • 2012-01-28
      相关资源
      最近更新 更多