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