2011-09-25 40 views
1

我正在学习Python,所以我可以轻松修改files from AIMA。我知道Java和C++,但是我发现存储库上的AIMA代码太混乱了。 Python代码看起来更简单,更优雅......但是,我不知道Python。我该如何玩这个.py文件?

我想导入search.py中的函数。

我试图创建一个search2.py文件是这样的:在文件夹上

import search 

class Problem2(Problem): 
    pass 

其中search.py​​是找来:

~/aima/aima-python$ python search2.py 
Traceback (most recent call last): 
    File "search2.py", line 3, in <module> 
    class Problem2(Problem): 
NameError: name 'Problem' is not defined 

这是为什么?

+0

可能与:http://stackoverflow.com/questions/3188929/why-import-when-you-need-to-use-the-full-name –

回答

7

当您使用import search时,您将名称search定义为从执行search.py​​创建的模块。如果有一个名为Problem类,你访问它search.Problem

import search 

class Problem2(search.Problem): 
    pass 

另一种方法是用这种说法定义Problem

from search import Problem 

,其执行search.py​​,然后在规定Problem您文件作为来自新创建的搜索模块的名称Problem。请注意,在此表单中,名称search未在您的文件中定义。

0

如果类Problem位于search模块中,你必须输入它要么像from search import Problem或使用这样的:

import search 

class Problem2(search.Problem): 
    pass 
3

你这里有两种选择:

  1. 相反import search,请写from search import Problem

  2. 代替class Problem2(Problem),写class Problem2(search.Problem)