class obj:
def __init__(self, a):
self.a = a
class obj2 :
def __init__(self, a):
self.a = a
pList = [obj(1),obj(2),obj(3),obj(4),obj(5)]
list = []
for i in pList:
obj2(i.a)
list.append(obj2)
for i in list :
print(i.a)
嗨,朋友。我是python newBie。我有这个代码,但它不起作用。
请教我..谢谢
Traceback (most recent call last):
File "D:/..py", line 18, in <module>
print(i.a)
AttributeError: type object 'obj2' has no attribute 'a'
Process finished with exit code 1
答案 0 :(得分:9)
因为您丢弃了在列表中创建的obj2
实例,然后追加类本身。它应该是:
for i in pList:
o2 = obj2(i.a)
list.append(o2)
请注意,如果您使用标准命名约定,调用Obj和Obj2类,这将更加明显。