在Python中测试变量类型

3 投票
7 回答
32686 浏览
提问于 2025-04-15 20:37

我正在为一个叫做“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) 吗?

7 个回答

3

几点事情:

  • 你有一个叫“type”的参数。这会遮盖掉Python内置的“type”功能,因为它是全局的,而局部变量会优先于全局变量。我猜这个错误是因为“type”被赋了一个字符串值。

  • 你为什么要打印错误信息呢?正确的处理错误的方法是抛出一个异常。

总的来说,我同意其他人的看法,通常在Python中进行类型检查是不推荐的。这种情况只在很少的情况下才需要。

8

Python是一种动态语言。明确测试变量类型并不是一个好主意。实际上,你写的代码应该设计得足够好,这样你就不需要去测试变量的类型了。

如果你之前使用的是C/C++/Java,可能需要花点时间来适应这一点。

13

这里不讨论“为什么”,但可以说:

  1. str 本身就是一种数据类型。你可以用 type(self.code) != str 来检查。
  2. 不过,更好的方法是用 isinstance(self.code, str) 来判断。

撰写回答