为什么调用`import random;random.random()` 抛出一个类型错误? [英] Why is calling `import random; random.random()` throwing a TypeError?

查看:112
本文介绍了为什么调用`import random;random.random()` 抛出一个类型错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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'>

即,randomrandom.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:

  1. python -mrandom 在当前目录中找到random.py,将其导入为random,并开始以运行__main__.
  2. 它看到import random并导入缓存的模块.
  3. print(random) 将模块对象的表示打印到标准输出.
  4. print(random.random)random 模块中查找 random 名称.它找到它(名称指的是模块本身.然后打印出来.
  1. python -mrandom finds random.py in the current directory, imports it as random and and starts to run it as __main__.
  2. It sees import random and imports the cached module.
  3. print(random) prints the representation of the module object to stdout.
  4. print(random.random) looks up random name in random module. It finds it (the name refers to the module itself. And it prints it.

解决方案是避免隐藏名称.避免隐藏标准名称以提高可读性.如果您可能在代码中使用第三方名称,请避免隐藏它们.

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()` 抛出一个类型错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆