为什么动态实例创建后isinstance会返回false?

时间:2016-09-29 00:36:07

标签: python-3.x inheritance

我在尝试基于给定字典创建和实例时遇到问题。

我目前的代码:

class Number(object):
    def __init__(self, value):
        self.value = value

    def evaluate(self):
        return self.value

    def to_dict(self):
        return self.value

class ArithmeticNode(object):
    OPERATORS_TO_CLASSES = dict(map(lambda cls: (cls.OPERATOR, cls),
                    ArithmeticNode.__subclasses__()))

    def __init__(self, val1, val2):
        self.val1 = val1 if isinstance(val1, ArithmeticNode) else Number(val1)
        self.val2 = val2 if isinstance(val2, ArithmeticNode) else Number(val2)

    def to_dict(self):
        v1 = self.val1.to_dict()
        v2 = self.val2.to_dict()
        return {self.OPERATOR: [v1, v2]}

    @staticmethod
    def from_dict(d):
        cls_dict = ArithmeticNode.OPERATORS_TO_CLASSES
        def create_node(d):
            nonlocal cls_dict
            if isinstance(d, dict):
                for operator, (left_val, right_val) in d.items():
                    cls_inst_to_create = cls_dict[operator]
                    value_1 = create_node(left_val)
                    value_2 = create_node(right_val)
                    return cls_inst_to_create(value_1, value_2)
            else:
                return d
        return create_node(d)

class AddNode(ArithmeticNode):
    OPERATOR = '+'
    def evaluate(self):
        return self.val1.evaluate() + self.val2.evaluate()

当我这样做时:

a = AddNode(3, AddNode(5, 3)) # Everything works just perfect
d = a.to_dict() # {'+': [3, {'+': [5, 3]}]}
c = ArithmeticNode.from_dict(d)
print(c) # <__main__.AddNode object at 0x7fac20def908>
# Trying to check if this is still the instance of ArithmeticNode
isinstance(c, ArithmeticNode) 
> False

所以我的问题是:在这种情况下,为什么isinstance会返回False:

a = AddNode(3, AddNode(5, 3))
isinstance(a, ArithmeticNode)
True

很抱歉,如果这对您来说很明显,但我无法找到原因。

0 个答案:

没有答案