我有一个我写过的类,MyEdge(它存储了两个节点来为一些图创建一条边),我正在努力弄清楚为什么 isinstance 似乎表现得不一致。
我有一个对象 new_road,当我问它时它认为它在 MyEdge 类中。
isinstance(new_road, my_graph.MyEdge)
返回假。
当我指向它时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)