我有一个编写的类,MyEdge(它存储了两个节点以使某些图成为边缘),并且我正在努力弄清楚为什么isinstance表现出不一致的现象。
我有一个对象new_road,当我问它时,它认为它在MyEdge类中。isinstance(new_road, my_graph.MyEdge)
返回False。
当我指向它的指针e0 = new_road, isinstance(e0, my_graph.MyEdge)
时,也会得到false,这至少是自洽的。
复制时,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)
应该为true。
为什么实例对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)
最佳答案
也许您在创建new_road和e1之间重新加载/重新导入/覆盖该类
In [1]: class C(object): pass
In [2]: a = C()
In [3]: class C(object): pass
In [4]: isinstance(a, C)
Out[4]: False
在此示例中,两个C()实例的
__class__
看起来相同,但是它们仍然不同。 id()
可能会帮助:id(type(e1)), id(type(new_road)), id(my_graph.MyEdge)
所有ID均应相同。
关于python - isinstance()的行为不符合我的预期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30110306/