我有一个变量type
,我想使用内置type()
函数
示例
def fun(inv):
log.debug('type of inv {}'.format(type(inv)))
type = 'int'
运行该函数时出现以下错误:
AttributeError: 'module' object has no attribute 'type'
答案 0 :(得分:8)
您的type
变量已覆盖*内置type
功能。但您仍然可以通过Python 2中的__builtin__
模块或Python 3中的builtins
访问原始文件。
Python 2:
>>> type = "string"
>>> type("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> import __builtin__
>>> __builtin__.type("test")
<type 'str'>
Python 3:
>>> type = "string"
>>> type("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> import builtins
>>> builtins.type("test")
<type 'str'>
但是,最好通过选择不同的变量名来避免这种情况。
还值得一提的是,在尝试将type
作为函数调用之后,您只分配给type
没有区别。在Python中,如果将名称绑定到该函数中的任何位置(并且未声明为全局),则该名称将作为局部变量绑定到该函数。因此,即使您只在函数的第二行中分配给type
,type
仍然是整个函数中的局部变量。
*严格来说,“隐藏”可能是一个更好的描述,因为内置的type
函数仍然存在,只是Python resolves variables names looking for local definition first, and built-ins last。
答案 1 :(得分:1)
如果为函数内的变量赋值,它将成为该函数中的局部变量。它将不再引用它的原始全局内置函数,即使您在函数末尾指定了一个新值。
您也必须收到此错误。
UnboundLocalError: local variable 'type' referenced before assignment
最佳做法是不要覆盖内置函数或模块。
答案 2 :(得分:0)
将内置函数用作变量名称不是一个好习惯。因此,您可以将变量名称从类型重命名为 _type