2017-10-05 169 views
1

我在访问对象的属性时遇到问题。该任务本身创建了一些比较多个对象属性的算法,但考虑到我无法访问这些属性,我甚至无法做到这一点。访问对象的对象数组属性在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' 

类似的代码如下:

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

无关的问题,但'[]'在默认参数'items'是_The相同instance_每次调用构造函数。 –

+0

与问题无关,但可能是需要修复的下一个错误,所以是的,要小心。 – Pablo

回答

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) 
+0

谢谢!调用该方法对我有效。至于代码的结构,这是分配实际上预先定义的非常粗略的版本。当我创作我的版本时,我没有想太多。再次感谢! – Sarchwalk