-4

我在一个简单的程序中遇到了 python 问题。该程序应该允许用户创建一个 Cow() 实例并在参数中为牛命名。

class Cow():
    def __init__(self, name):
        self.name = name
        if self.name == None:
            raise NoNameCowError("Your cow must have a name")


    def speak(self):
        print self.name, "says moo"

现在当我做

cow.Cow("Toby")

我得到错误

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    cow.Cow("Toby")
  File "C:\Users\Samga_000\Documents\MyPrograms\cow.py", line 8, in __init__
    self.name = name
AttributeError: Cow instance has no attribute 'name'

帮助?我原本以为我对异常做错了什么,但似乎并非如此。提前致谢。

4

3 回答 3

1

我认为您修改了源代码并没有重新加载模块:

越野车版本:

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")
于 2013-11-01T15:59:30.737 回答
0

I'm staring at the name check; this object requires the name argument does it not?

if self.name == None:
        raise NoNameCowError("Your cow must have a name")

I'm a little Python thick, but that looks like a required arg.

于 2013-11-01T15:51:44.300 回答
0

当您声明 Cow 时,您需要在括号中传递对象:

class Cow(object):
    rest of code.

这样 Python 就知道你声明的类是一个具有属性和方法的对象。

于 2016-11-06T18:44:28.970 回答