我对Python的import random函数有问题。似乎import random
和from random import random
正在导入不同的内容。我目前正在使用Python2.7.3
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> random()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
random()
NameError: name 'random' is not defined
>>> random.randint(1,5)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
random.randint(1,5)
NameError: name 'random' is not defined
>>> import random
>>> random()
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
random()
TypeError: 'module' object is not callable
>>> random.randint(1,5)
2
>>> from random import random
>>> random()
0.28242411635200193
>>> random.randint(1,5)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
random.randint(1,5)
AttributeError: 'builtin_function_or_method' object has no attribute 'randint'
>>>
import random
导入random模块,其中包含与随机数生成有关的各种操作。其中有random()函数,它生成0到1之间的随机数。以这种方式进行导入需要使用语法
random.random()
。随机函数也可以从模块中单独导入:
这允许您直接调用
random()
。random module包含一个名为
random()
的函数,因此您需要知道是已将模块导入到命名空间中,还是已从模块导入函数。import random
将导入随机模块,而from random import random
将专门从模块导入随机函数。因此,您将能够执行以下操作之一:
或者。。。
问题是这里有两种东西叫做随机:一种是模块本身,另一种是模块内的函数。名称空间中不能有两个同名的对象,因此必须选择其中一个。
相关问题 更多 >
编程相关推荐