-2
对于程序, 我有三个文件dice.py
hog.py
ucb.py
坐在同一个文件夹中。查询python中的导入功能
""" hog.py"""
from dice import four_sided_dice, six_sided_dice
from ucb import interact
def roll_dice(num_rolls, dice=six_sided_dice, who='Boss Hogg'):
"""Calculate WHO's turn score after rolling DICE for NUM_ROLLS times.
num_rolls: The number of dice rolls that will be made; at least 1.
dice: A function of no args and returns an integer outcome.
who: Name of the current player, for commentary.
"""
score = 0
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls > 0, 'Must roll at least once.'
for i in range(0, num_rolls):
temp = dice()
score += temp
print(temp)
return score
"""dice.py"""
from random import randint
def make_fair_dice(sides):
"""Return a die that returns 1 to SIDES with equal chance."""
assert type(sides) == int and sides >= 1, 'Illegal value for sides'
def dice():
return randint(1,sides)
return dice
four_sided_dice = make_fair_dice(4)
six_sided_dice = make_fair_dice(6)
在hog.py
,语法之一是,
from dice import four_sided_dice, six_sided_dice
,当我说,
>>> python -i hog.py
所有名称中hog.py模块定义得到附加到__main__
模块的全局框架。
我的问题:
当上面import语句在hog.py
被碰到,
1) 不Python的负载function make_fair_dice()
在dice.py
定义为__main__
模块的一部分?或单独的模块?
2) python解释器如何知道,dice.py
文件在同一个文件夹中?应该做什么,如果我需要从不同的文件夹中选择dice.py
?
请考虑[阅读文档](https://docs.python.org/2/tutorial/modules.html)。此外,您可以测试第1点 - 如果您尝试直接调用函数make_fair_dice(),会发生什么情况? – jonrsharpe
你应该考虑给你的问题提供更好的标题 - 参见例如http://stackoverflow.com/help/how-to-ask。 “查询......”不是很有帮助 - 尽量简洁地总结实际问题。 – jonrsharpe
@jonrsharpe这里是我对测试点1的观察,在我运行'>>> python -i hog.py'后,'hog.py'文件中的所有定义都是'__main__'模块的一部分。在'hog.py'文件中,当我从'ucb.py'或'dice.py'模块中输入'任何名称(函数)并调用该函数时,该函数在'ucb'或' dice'模块,但不在'__main__'模块的范围内。因此,在查询中的上述语法中,带有名称的导入就像指向__main__'模块外的模块中的函数的指针。所有这些都是使用全局变量'__name__'的值验证的。 – overexchange