为了安全起见,我在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
尝试TypeError
或repr()
str()
时,Point
会一直被提升。发生了什么,我该如何解决?
编辑: 整个Conversion.py目前包含上述getStateAsStr片段。导入位于底部以防止循环导入错误。
非常重要:如果从Conversion.py运行,它就像一个魅力。从pointsys文件运行会从getStateAsStr
生成TypeError以下是包含Point
类的整个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