【发布时间】:2019-06-05 17:47:20
【问题描述】:
我在 Python 中使用timeit,遇到了一个奇怪的问题。
我定义了一个简单的函数add。 timeit 在我传递 add 两个字符串参数时起作用。但是当我传递add 两个int 参数时,它会引发ValueError: stmt is neither a string nor callable。
>>> import timeit
>>> def add(x,y):
... return x + y
...
>>> a = '1'
>>> b = '2'
>>> timeit.timeit(add(a,b))
0.01355926995165646
>>> a = 1
>>> b = 2
>>> timeit.timeit(add(a,b))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/anaconda/lib/python3.6/timeit.py", line 233, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "/anaconda/lib/python3.6/timeit.py", line 130, in __init__
raise ValueError("stmt is neither a string nor callable")
ValueError: stmt is neither a string nor callable
为什么参数类型在这里很重要?
【问题讨论】:
-
为什么对象的类型不重要?