为了安全起见,我用 Python 编写了一些涉及类型检查的代码,但其中一个在一个地方一直失败,但也在几乎同一个地方工作。
此检查适用于 Point 类:
def __repr__(self) :
print('we be an instance: {}'.format(isinstance(self,Point)))
return "(point: state:{}; conns:{})".format(Conversion.getStateAsStr(self), connections[self])
并成功打印出来we be an instance: true
。
但是,该方法Conversion.getStateAsStr
报告给定对象不是Point
:
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
ATypeError
在尝试repr()
或str()
a时被持续提出Point
。发生了什么事,我该如何解决?
编辑:整个 Conversion.py 目前由上面的 getStateAsStr 片段组成。导入位于底部以防止循环导入出现错误。
非常重要:如果从 Conversion.py 运行,它就像一个魅力。从 pointsys 文件运行会产生来自 getStateAsStr 的 TypeError
这是包含类的整个 pointsys.py 文件Point
:
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