我认为您修改了源代码并没有重新加载模块:
越野车版本:
class Cow():
def __init__(self, name):
if self.name == None:
raise NoNameCowError("Your cow must have a name")
def speak(self):
print self.name, "says moo"
>>> import so
按预期引发错误:
>>> so.Cow('abc1')
Traceback (most recent call last):
File "<ipython-input-4-80383f90b571>", line 1, in <module>
so.Cow('abc1')
File "so.py", line 3, in __init__
if self.name == None:
AttributeError: Cow instance has no attribute 'name'
现在让我们修改源代码并添加这一行self.name = name:
>>> import so
>>> so.Cow('abc1')
Traceback (most recent call last):
File "<ipython-input-6-80383f90b571>", line 1, in <module>
so.Cow('abc1')
File "so.py", line 3, in __init__
self.name = name
AttributeError: Cow instance has no attribute 'name'
诶!还是同样的错误?那是因为 python 仍在使用旧.pyc文件或缓存的模块对象。只需重新加载模块,更新的代码就可以正常工作:
>>> reload(so)
<module 'so' from 'so.py'>
>>> so.Cow('dsfds')
<so.Cow instance at 0x8b78e8c>
来自文档:
注意 出于效率原因,每个模块在每个解释器会话中只导入一次。因此,如果你改变你的模块,你必须重新启动解释器——或者,如果它只是你想要交互测试的一个模块,使用reload(),例如reload(modulename)。
您的代码的更好版本:
class Cow():
def __init__(self, name=None): #Use a default value
self.name = name
if self.name is None: #use `is` for testing against `None`
raise NoNameCowError("Your cow must have a name")