python属性错误_Python属性错误

我想你修改了源代码,没有重新加载模块:

小车版本: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")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值