Python:实例没有属性

2024-05-31 23:46:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python中的类中的list有问题。这是我的代码:

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

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

像这样的东西。我有个错误说:

AttributeError: Residues instance has no attribute 'atoms'

Tags: instance代码nameselfdef错误listclass
1条回答
网友
1楼 · 发布于 2024-05-31 23:46:01

您的类没有__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
>>> 

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

为了确保您始终拥有一个atoms列表,您可以添加一个构造函数:

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

相关问题 更多 >