在Python中测试变量类型

3 python testing variables

我正在为'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'
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

----感谢您的帮助,但是:-----

这适用于isinstance(item,list)或isinstance(item,tuple)吗?

ken*_*ytm 10

没有回答"为什么",但是

  1. str本身已经是一种类型.您可以使用type(self.code) != str
  2. 但更好的方法是使用isinstance(self.code, str).

  • 不总是.有时候你**需要**进行类型检查,比如在编码对象时(想想JSON). (6认同)

Xol*_*lve 8

Python是一种动态语言.明确地测试类型是个坏主意.事实上,您编写的代码本身应该是您不需要测试变量类型的.

如果你来自C/C++/Java那么需要一些时间来克服它.

  • +1:不测试类型.如果他们错了,它将**崩溃.另一方面,它们可能是一种新型,完全兼容,并且您已经阻止了完全兼容的用例. (5认同)
  • 为了使S. Lott的观点具体化:如果不是因为过度热心的类型检查,所发布的类可能与unicode字符串一起使用. (2认同)