Python:实例没有属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12938917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:13:49  来源:igfitidea点击:

Python: instance has no attribute

pythonclassattributeerror

提问by Mantas Marcinkus

I have a problem with list within a class in python. Here's my code :

我在 python 类中的列表有问题。这是我的代码:

class Residues:
    def setdata(self, name):
        self.name = name
        self.atoms = list()

a = atom
C = Residues()
C.atoms.append(a)

Something like this. I get an error saying:

像这样的东西。我收到一条错误消息:

AttributeError: Residues instance has no attribute 'atoms'

采纳答案by NullUserException

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atomsis not present. You'd have to do C.setdata('something')so C.atomsbecomes available.

您的类没有__init__(),因此在实例化时,该属性atoms不存在。你必须这样C.setdata('something')C.atoms变得可用。

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

不像在 Java 这样的语言中,您在编译时就知道对象将具有哪些属性/成员变量,而在 Python 中,您可以在运行时动态添加属性。这也意味着同一类的实例可以具有不同的属性。

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atomslist you could add a constructor:

为了确保您始终拥有一个atoms列表(除非您将其弄乱,否则这是您自己的错)您可以添加一个构造函数:

def __init__(self):
    self.atoms = []