我在訪問對象的屬性時遇到問題。該任務本身創建了一些比較多個對象屬性的算法,但考慮到我無法訪問這些屬性,我甚至無法做到這一點。訪問對象的對象數組屬性在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我的任務。
問題:
- 如何訪問從list_of_things任一屬性?
- 如何確保我正在訪問屬性? (將打印的工作還是會給出地址)
無關的問題,但'[]'在默認參數'items'是_The相同instance_每次調用構造函數。 –
與問題無關,但可能是需要修復的下一個錯誤,所以是的,要小心。 – Pablo