我想你修改了源代码,没有重新加载模块:
小车版本: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
按预期引发错误:
^{pr2}$
现在让我们修改源代码并添加以下行self.name = name:>>> import so
>>> so.Cow('abc1')
Traceback (most recent call last):
File "", line 1, in
so.Cow('abc1')
File "so.py", line 3, in __init__
self.name = name
AttributeError: Cow instance has no attribute 'name'
啊!还是同样的错误?这是因为python仍然使用旧的.pyc文件或缓存的模块对象。只需重新加载模块,更新的代码就可以正常工作:>>> reload(so)
>>> so.Cow('dsfds')
Note For efficiency reasons, each module is only imported once per
interpreter session. Therefore, if you change your modules, you must
restart the interpreter – or, if it’s just one module you want to test
interactively, use reload(), e.g. 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")