我是 Python 新手.我写了一个小脚本来生成十个随机浮点值,但它一直失败.这是脚本:
I'm new to Python. I wrote a small script to generate ten random float values, but it keeps failing. Here's the script:
import random for i in range(10): x = random.random() print x这是错误信息:
TypeError: 'module' object is not callable'.我看不出是什么问题.我很确定随机存在!
I can't see what the problem is. I'm pretty sure random exists!
我的版本是 Python 2.7.6.
My version is Python 2.7.6.
推荐答案如果将以下代码保存到 random.py 中:
If you save the following code into random.py:
import random print(__name__) print(random) print(random.random)并运行它,然后它会打印如下内容:
and run it then it prints something like:
random <module 'random' from '/.../python/import/name-shadowing/random.py'> <module 'random' from '/.../python/import/name-shadowing/random.py'> __main__ <module 'random' from '/.../python/import/name-shadowing/random.py'> <module 'random' from '/.../python/import/name-shadowing/random.py'>即,random 和 random.random 都指的是同一个模块——你的本地 random.py 阴影 random 来自标准库的模块.
i.e., both random and random.random refers to the same module -- your local random.py that shadows random module from the standard library.
也许它的工作原理如下:
Perhaps it works as follows:
解决方案是避免隐藏名称.避免隐藏标准名称以提高可读性.如果您可能在代码中使用第三方名称,请避免隐藏它们.
The solution is to avoid shadowing the names. Avoid shadowing the standard names for readability. And avoid shadowing 3rd-party names if you might use them in your code.
如果当前目录不在 sys.path 中,则导入 stdlib 模块:
If the current directory is not in sys.path then it imports stdlib module:
import sys sys.path.pop(0) # assume the script directory is the first in the Python path import random print(__name__) print(random) print(random.random)输出
__main__ <module 'random' from '/usr/lib/python3.4/random.py'> <built-in method random of Random object at 0x1aaf7f8>注意:仅用于说明.避免修改脚本中的 sys.path.
Note: it is only for illustration. Avoid modifying sys.path in your scripts.
更多推荐
为什么调用`import random;random.random()` 抛出一个类型错误?
发布评论