我正在使用 Squish 框架为应用程序编写自动测试。在测试脚本中有代码调用randrange
:
a = 5.0
random.randrange( int(a) )
由于这个电话,我在网上lib/python2.6/random.py:171
遇到了一个非常奇怪的错误:
TypeError: int() argument must be a string or a number, not 'int'
random.py 中的上下文,第 171 行是randrange
函数中的第一行代码:
def randrange(self, start, stop=None, step=1, int=int, default=None,
maxwidth=1L<<BPF):
"""Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.
Do not supply the 'int', 'default', and 'maxwidth' arguments.
"""
# This code is a bit messy to make it fast for the
# common case while still doing adequate error checking.
istart = int(start) # <---this is line 171
if istart != start:
raise ValueError, "non-integer arg 1 for randrange()"
if stop is default:
...
当然我用调试器控制台检查过,类型确实是int
:
>>> __builtin__.type(start)
<type 'int'>
>>>
经过一段时间的谷歌搜索后,我在 Squish API 文档中得到了答案:
Python 程序员应该知道,整数类型转换是
int(x)
行不通的;使用x = cast(x, int)
orx = cast(x, "int")
代替。或者,如果您愿意,请执行import __builtin__
,然后使用x = __builtin__.int(x)
.int
(这是必要的,因为 Squish在 Python 中实现了它自己的对象。)
那么好吧。但我的问题是:如果存在名称冲突,如何检查 Python 对象类型?我怎么知道<type 'something'>
是在哪里声明的?