Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
属性错误Python_Python - Fatal编程技术网

属性错误Python

属性错误Python,python,Python,我在一个简单的程序中遇到了python问题。程序应该允许用户创建make a Cow()实例,并在参数中为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):

我在一个简单的程序中遇到了python问题。程序应该允许用户创建make a Cow()实例,并在参数中为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'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
牛,牛(“托比”)
文件“C:\Users\Samga\u 000\Documents\MyPrograms\cow.py”,第8行,在\uu init中__
self.name=名称
AttributeError:Cow实例没有属性“name”

帮忙?我本来以为我做了一些例外的错误,但似乎不是那样。提前谢谢。

我正盯着姓名检查;此对象需要name参数,不是吗

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

我有点像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
按预期引发错误:

>>> 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'
嗯!!还是同样的错误?这是因为python仍在使用旧的
.pyc
文件或缓存的模块对象。只需重新加载模块,更新后的代码即可正常工作:

>>> reload(so)
<module 'so' from 'so.py'>
>>> so.Cow('dsfds')
<so.Cow instance at 0x8b78e8c>

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

class Cow(object):
    rest of code.

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

可以正常工作。除此之外:您的代码不会触发speak()。你在做什么和你的代码上撒谎。你当前的代码看起来不错,请尝试重新加载模块或删除
cow.pyc
文件,然后重试。你的程序不完整,导致许多人猜测问题出在哪里。请提供一个简短、完整的程序来演示错误。请复制粘贴(不要重新键入)程序及其输出,并说明预期输出。有关更多信息,请参阅。
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")
class Cow(object):
    rest of code.