访问对象的对象数组属性会在python中给出属性错误

时间:2017-10-05 17:05:51

标签: python python-3.x oop object

我在访问对象的属性时遇到问题。赋值本身正在创建一些比较多个对象的算法。属性,但考虑到我还没有能够访问这些属性,我甚至无法做到这一点。

我写了一段代码,类似于我在下面使用的代码。当我尝试访问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'

类似的代码如下:

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

class ThingOfThings:
    def __init__(self, items=[]):
        self.items = items
    def get_thing(self, thing):
        self.items += [thing]

list_of_things = ThingOfThings()

one_thing = Thing()
for i in range(2):
    list_of_things.get_thing(one_thing.give_a_thing)
print(list_of_things.items[0].attribute1)

我无法更改任何一个班级,但会为我的作业添加def。

问题:

  1. 如何从list_of_things中访问任一属性?
  2. 如何确保我访问该属性? (将打印工作或将提供地址)

1 个答案:

答案 0 :(得分:4)

因此,基本问题正是错误信息所暗示的内容:

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

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

one_thing = Thing()
for i in range(2):
    list_of_things.get_thing(one_thing.give_a_thing)

意识到one_thing.give_a_thing返回方法本身,您想调用方法

one_thing = Thing()
for i in range(2):
    list_of_things.get_thing(one_thing.give_a_thing())

除此之外,这段代码非常奇怪。为什么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)