2014-07-14 20 views
-2

对于程序, 我有三个文件dice.pyhog.pyucb.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

+5

请考虑[阅读文档](https://docs.python.org/2/tutorial/modules.html)。此外,您可以测试第1点 - 如果您尝试直接调用函数make_fair_dice(),会发生什么情况? – jonrsharpe

+0

你应该考虑给你的问题提供更好的标题 - 参见例如http://stackoverflow.com/help/how-to-ask。 “查询......”不是很有帮助 - 尽量简洁地总结实际问题。 – jonrsharpe

+0

@jonrsharpe这里是我对测试点1的观察,在我运行'>>> python -i hog.py'后,'hog.py'文件中的所有定义都是'__main__'模块的一部分。在'hog.py'文件中,当我从'ucb.py'或'dice.py'模块中输入'任何名称(函数)并调用该函数时,该函数在'ucb'或' dice'模块,但不在'__main__'模块的范围内。因此,在查询中的上述语法中,带有名称的导入就像指向__main__'模块外的模块中的函数的指针。所有这些都是使用全局变量'__name__'的值验证的。 – overexchange

回答

0

请看下面的代码:

from dice import four_sided_dice, six_sided_dice 

print four_sided_dice() # OK 
print six_sided_dice() # OK 

my_dice = make_fair_dice(8) # NameError: name 'make_fair_dice' is not defined 

既然你明确地导入只有两个名字:four_sided_dicesix_sided_dice,名称make_fair_dice将不可用,从而导致NameError

但是,由于这是一个导入语句,因此将执行整个dice.py模块。这意味着加载了程序make_fair_dice。它只是无法直接呼叫。现在,如果您隐导入骰子模块,那么一切都是可供选择:

import dice 
my_dice = dice.make_fair_dice(8) # OK 

至于你的第二个问题,请大家看看module search path文档。