Python 为什么这个物体既是点又不是点?
为了安全起见,我用Python编写了一些涉及类型检查的代码,但其中一个代码在一个点上始终失败,但也在几乎相同的点上工作 此检查适用于Point类:Python 为什么这个物体既是点又不是点?,python,class,Python,Class,为了安全起见,我用Python编写了一些涉及类型检查的代码,但其中一个代码在一个点上始终失败,但也在几乎相同的点上工作 此检查适用于Point类: def __repr__(self) : print('we be an instance: {}'.format(isinstance(self,Point))) return "(point: state:{}; conns:{})".format(Conversion.getStateAsStr(self), connectio
def __repr__(self) :
print('we be an instance: {}'.format(isinstance(self,Point)))
return "(point: state:{}; conns:{})".format(Conversion.getStateAsStr(self), connections[self])
并成功打印出我们是一个实例:true
但是,方法Conversion.getStateAsStr
报告给定对象不是点
:
def getStateAsStr(p) :
if not isinstance(p, Point) :
raise TypeError("Non-point")
if p.state : # state is a var in Point
return "On"
return "Off"
import pointsys
from pointsys import Point
尝试repr()
或str()
APoint
时,会持续引发TypeError
。发生了什么事,我该如何解决
编辑:
整个Conversion.py当前包含上述getStateAsStr代码段。导入位于底部,以防止循环导入出错
非常重要:如果从Conversion.py运行,它就像一个符咒。从pointsys文件运行会从getStateAsStr生成TypeError
下面是包含点
类的整个pointsys.py文件:
connections = {}
def writeConnection(point, connList) :
connections[point] = connList
def addConnection(point, point2) :
if point2 not in connections[point] :
connections[point].append(point2)
else :
print("Skipping point {}".format(point2))
def remConnection(point, point2) :
connections[point].remove(point2)
class Point():
def __init__(self) :
self.state = Off
writeConnection(self, [])
def __repr__(self) :
print('we be an instance: {}'.format(isinstance(self,Point)))
return "(point: state:{}; conns:{})".format(Conversion.getStateAsStr(self), connections[self])
"""
Makes or removes a connection between this point and p2
"""
def markConnection(self, p2, connected) :
if connected :
addConnection(self, p2)
elif not connected :
remConnection(self, p2)
"""
Returns if this point is connected to p2
"""
def isConnected(self, p2) :
return p2 in connections[self]
"""
Sets the state of this point and it's connections
"""
def pushState(self, state) :
self.state = state
for connection in connections[self][:] :
connection.pushState(state)
import Conversion
from State import Off, On, Connected, Unconnected
我试着用一个基本点类来复制你所得到的错误,但是我没能做到。我猜您遗漏了一些代码,而这些代码正是导致您出现问题的原因。你能发布一个更完整的代码示例吗?据我所知,pointsys是你已经开发并正在使用的一些内部模块/包。您还使用了一种称为转换的方法。仍然有很多信息丢失。我认为你不想分享项目的内部实施,你是对的。但是如果没有看到代码的一些结构,就很难确定这个错误的原因。好的,我将补充一点。我只是不想像以前那样让问题负担过重。你考虑得太周到了:)但是有很多内部缺少,问题肯定出在这些内部,因为这个错误不能用基点类重现。调用函数
getStateAsStr
的代码是什么?您确定正在传递一个点
实例吗?