2017-10-05 164 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