Python:实例没有属性 [英] Python: instance has no attribute

查看:526
本文介绍了Python:实例没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中的类中有一个问题。这是我的代码:

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

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'


推荐答案

您的类没有 __ init __(),所以在实例化的时候,属性 atoms 不存在。你必须做 C.setdata('something')所以 C.atoms 变得可用。

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

>>> 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类似的语言不同,在编译时你知道对象会有什么属性/成员变量,在Python中,您可以在运行时动态添加属性。这也意味着同一个类的实例可以有不同的属性。

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.

为了确保你总是有(除非你把它弄乱了,那么它是你自己的错误) atoms 列表,您可以添加一个构造函数:

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

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

这篇关于Python:实例没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆