在Python中测试变量类型
在Python中测试变量类型
我正在为类'Room'创建一个初始化函数,并发现程序无法接受我对输入变量的测试。
为什么会这样呢?
def __init__(self, code, name, type, size, description, objects, exits): self.code = code self.name = name self.type = type self.size = size self.description = description self.objects = objects self.exits = exits #检查输入错误: if type(self.code) != type(str()): print '在rooms.py模块中发现错误!' print '错误编号:110' elif type(self.name) != type(str()): print '在rooms.py模块中发现错误!' print '错误编号:111' elif type(self.type) != type(str()): print '在rooms.py模块中发现错误!' print '错误编号:112' elif type(self.size) != type(int()): print '在rooms.py模块中发现错误!' print '错误编号:113' elif type(self.description) != type(str()): print '在rooms.py模块中发现错误!' print '错误编号:114' elif type(self.objects) != type(list()): print '在rooms.py模块中发现错误!' print '错误编号:115' elif type(self.exits) != type(tuple()): print '在rooms.py模块中发现错误!' print '错误编号:116'
当我运行这个程序时,我得到了这个错误:
Traceback (most recent call last): File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 148, inmyRoom = Room(101, 'myRoom', 'Basic Room', 5, ' ', myObjects, myExits) File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 29, in __init__ if type(self.code) != type(str()): TypeError: 'str' object is not callable
---- 感谢你的帮助,但是: -----
这是否适用于isinstance(item, list)或isinstance(item, tuple)?