在python中,访问对象数组的objects属性会导致属性错误

2024-09-30 22:16:39 发布

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

我在访问对象属性时遇到问题。任务本身正在创建一系列算法来比较多个对象的属性,但是考虑到我还不能访问这些属性,我甚至走不了那么远。在

我写了一段代码,与下面我正在处理的代码类似。当我试图访问list_of_things.items[0].attribute1时,我遇到了问题。我试图打印只是为了确保我正确地访问项目,但我得到了以下错误:

Traceback (most recent call last):
  File "./test.py", line 22, in <module>
    print(list_of_things.items[0].attribute1)
AttributeError: 'function' object has no attribute 'attribute1'

类似代码如下:

^{pr2}$

我不能改变任何一个班级,但我将增加我的作业定义。在

问题:

  1. 我如何从清单中访问任意一个属性?在
  2. 如何确保访问属性?(将打印工作还是提供地址)

Tags: of项目对象代码算法most属性错误
1条回答
网友
1楼 · 发布于 2024-09-30 22:16:39

所以,根本问题就是错误信息的含义:

AttributeError: 'function' object has no attribute 'attribute1' 

这是因为items[0].attribute1试图访问函数对象上的attribute,因为items[0]是一个函数对象。注:

^{pr2}$

认识到one_thing.give_a_thing返回方法本身,您希望调用该方法

^{3}$

除此之外,这段代码的结构非常奇怪。为什么give_a_thing只是返回对象本身?这意味着您的list_of_things将是一个包含对同一对象的多个引用的列表。在

你可能想要

class Thing:
    def __init__(self, attribute1='y', attribute2='n'):
        self.attribute1 = attribute1
        self.attribute2 = attribute2


class ThingOfThings:
    def __init__(self, items=None):
        if items is None: # watch out for the mutable default argument
            items = []
        self.items = items
    def add_thing(self, thing): # use a better name
        self.items.append(thing) # don't create a needless intermediate, single-element list

然后简单地:

list_of_things = ThingOfThings()

for _ in range(2): # style tip: use _ if iterator variable is not used
    list_of_things.add_thing(Thing()) # create *new* Thing each iteration

print(list_of_things.items[0].attribute1)

相关问题 更多 >