简体   繁体   English

这个简单的python代码,为什么不起作用?

[英]this simple python code, why it doen't work?

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)

Hi friend. 你好,朋友。 Im python newBie. 我是python newBie。 I have this code but it doesn't work. 我有此代码,但无法正常工作。
please teach me.. thank you 请教我..谢谢

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

Because you throw away the instance of obj2 that you create in the list, and then append the class itself. 因为您丢弃了在列表中创建的obj2实例,然后附加了本身。 It should be: 它应该是:

for i in pList:
    o2 = obj2(i.a)
    list.append(o2)

Note that this would be more obvious if you used standard naming conventions, calling your classes Obj and Obj2. 请注意,如果您使用标准命名约定来调用类Obj和Obj2,这将更加明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM