首页 / PYTHON / 在Python中测试变量类型
在Python中测试变量类型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Python中测试变量类型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1718字,纯文字阅读大概需要3分钟。
内容图文
![在Python中测试变量类型](/upload/InfoBanner/zyjiaocheng/766/993111dfb3ec432bb2202be8f49953f4.jpg)
我正在为’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
#Check for input errors:
if type(self.code) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 110'
elif type(self.name) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 111'
elif type(self.type) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 112'
elif type(self.size) != type(int()):
print 'Error found in module rooms.py!'
print 'Error number: 113'
elif type(self.description) != type(str()):
print 'Error found in module rooms.py!'
print 'Error number: 114'
elif type(self.objects) != type(list()):
print 'Error found in module rooms.py!'
print 'Error number: 115'
elif type(self.exits) != type(tuple()):
print 'Error found in module rooms.py!'
print 'Error number: 116'
当我运行这个时,我收到此错误:
Traceback (most recent call last):
File "/Users/Jasper/Development/Programming/MyProjects/Game Making Challenge/Europa I/rooms.py", line 148, in <module>
myRoom = Room(101, 'myRoom', 'Basic Room', 5, '<insert description>', 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)吗?
解决方法:
没有回答“为什么”,但是
> str本身已经是一种类型了.你可以使用type(self.code)!= str
>但更好的方法是使用isinstance(self.code,str).
内容总结
以上是互联网集市为您收集整理的在Python中测试变量类型全部内容,希望文章能够帮你解决在Python中测试变量类型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。