2010-10-07 82 views
4

我刚刚开始学习Python,但我已经遇到了一些错误。我已经做了,其内容如下称为pythontest.py文件:为什么我在导入类时遇到名称错误?

class Fridge: 
    """This class implements a fridge where ingredients can be added and removed individually 
     or in groups""" 
    def __init__(self, items={}): 
     """Optionally pass in an initial dictionary of items""" 
     if type(items) != type({}): 
      raise TypeError("Fridge requires a dictionary but was given %s" % type(items)) 
     self.items = items 
     return 

我想创建交互式终端类的新实例,所以我跑在我的终端以下命令: python3

>> import pythontest 
>> f = Fridge() 

我得到这个错误:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'Fridge' is not defined 

交互式控制台找不到我做的类。虽然导入工作成功。没有错误。

回答

4

你需要做的:

>>> import pythontest 
>>> f = pythontest.Fridge() 

奖励:你的代码会这样写得更好:

def __init__(self, items=None): 
    """Optionally pass in an initial dictionary of items""" 
    if items is None: 
     items = {} 
    if not isinstance(items, dict): 
     raise TypeError("Fridge requires a dictionary but was given %s" % type(items)) 
    self.items = items 
+0

只是好奇进口,为什么项目= {}在参数列表一个坏主意? – 2010-10-07 19:41:53

+0

@RevolXadda:因为函数参数只处理一次。如果你给它可变的东西,它会在函数调用之间发生变异(如果你改变了它)。观察'def foo(d = [])的输出:d.append('foo');当你连续多次调用它时打印d'。 – Daenyth 2010-10-07 19:52:24

+0

@Daenyth:谢谢!我完全忘记了这一点。 – 2010-10-07 20:00:45

2

尝试

import pythontest 
f=pythontest.Fridge() 

当你import pythontest,变量名pythontest被加入到全局命名空间,并在模块pythontest的参考。要访问pythontest名称空间中的对象,必须在前面加上pythontest后跟一个句点。

import pythontest在模块中导入模块和访问对象的首选方法。

from pythontest import * 

应该(几乎)总是要避免。我认为可以接受的唯一情况是在包的内部设置变量__init__,以及在交互式会话中工作时。 from pythontest import *应该避免的原因之一是难以知道变量来自哪里。这使得调试和维护代码更困难。它也不协助嘲笑和单元测试。 import pythontest给出了pythontest它自己的命名空间。正如Python的禅说:“命名空间是一个好主意 - 让我们做更多的!”

0

你应该导入的名字,即或是

import pythontest 
f= pythontest.Fridge() 

,或者

from pythontest import * 
f = Fridge() 
7

似乎没有人提,你可以做

from pythontest import Fridge 

这样,你现在可以在命名空间中直接调用Fridge()不使用通配符

相关问题