isinstance()的行为不符合我的预期

时间:2015-05-07 19:44:51

标签: python isinstance

我有一个我写过的课程,MyEdge(它存储了两个节点以便为某些图形设置优势),而我正在努力弄清楚为什么实例似乎行为不一致。

我有一个对象new_road,当我问它时,它认为它在MyEdge类中。 isinstance(new_road, my_graph.MyEdge)返回False。

当我指向它时,e0 = new_road, isinstance(e0, my_graph.MyEdge),我也会得到假,这至少是自我一致的。

当我复制时,e1 = my_graph.MyEdge(new_road.nodes), isinstance(e1,my_graph.MyEdge)返回true。

new_road,e0和e1都返回它们的类是'my_graph.MyEdge',所以似乎isinstance(new_road,my_graph.MyEdge)应该是真的。

为什么isinstance以不同方式处理e1和new_road1?

ipdb> new_road.__class__
<class 'my_graph.MyEdge'>

ipdb> e1 = my_graph.MyEdge(new_road.nodes)

ipdb> e1 is new_road
False

ipdb> e1 == new_road
True

ipdb> e1.__class__
<class 'my_graph.MyEdge'>

ipdb> new_road.__class__
<class 'my_graph.MyEdge'>

ipdb> isinstance(e1,my_graph.MyEdge)
True

ipdb> isinstance(new_road,my_graph.MyEdge)
False

ipdb> new_road1.__class__ is my_graph.MyEdge 
False

ipdb> e1.__class__ is my_graph.MyEdge 
True

我不知道它是否有用,但这是我的MyEdge类的代码:

class MyEdge(object):
    """ keeps the properties of the edges in a parcel."""

    def __init__(self, nodes):
        self.nodes = tuple(nodes)
        self.parcel1 = None
        self.parcel2 = None
        self.road = False
        self.barrier = False

    @lazy_property
    def length(self):
        return mgh.distance(self.nodes[0], self.nodes[1])

    @lazy_property
    def rads(self):
        return math.atan((self.nodes[0].y - self.nodes[1].y) /
                         (self.nodes[0].x - self.nodes[1].x))

    def __repr__(self):
        return "MyEdge with nodes {} {}".format(self.nodes[0], self.nodes[1])

    def __eq__(self, other):
        return ((self.nodes[0] == other.nodes[0] and
                 self.nodes[1] == other.nodes[1]) or
                (self.nodes[0] == other.nodes[1] and
                 self.nodes[1] == other.nodes[0]))

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        return hash(self.nodes)

1 个答案:

答案 0 :(得分:4)

也许您在创建new_road和e1

之间重新加载/重新导入/覆盖该类
#!/bin/bash

在此示例中,两个C()实例中的In [1]: class C(object): pass In [2]: a = C() In [3]: class C(object): pass In [4]: isinstance(a, C) Out[4]: False 看起来相同,但它们仍然不同。 __class__可能有所帮助:

id()

所有ID都应该相同。