简体   繁体   English

Class X 没有属性 Y

[英]Class X not have attributes Y

I don't understand this strange things...I've this class:我不明白这些奇怪的事情......我有这个 class:

class cChallenge:
    def __init__(self, Id:int = 0 , Difficulty:str = '', Title:str = '',
                 Challenge:str = '', Url:str = '', Solved:bool = False):
        self.Id = Id
        self.Difficulty = Difficulty
        self.Title = Title
        self.Challenge = Challenge
        self.Url = Url
        self.Solved = Solved

Everything works fine so I've pushed all my generated cChallenge elements into a list: cList .一切正常,所以我已将所有生成的cChallenge元素推入一个列表: cList If I query the list for single object everything works fine:如果我在列表中查询单个 object 一切正常:

print(cList[1].Id)
>> 380

but if I use list comp:但如果我使用列表组合:

print([x.Id for x in cList])
>> AttributeError: type object 'cChallenge' has no attribute 'Id'

[https://pastebin.com/cGuhPAG8] That's the link if someone want to try [https://pastebin.com/cGuhPAG8] 如果有人想尝试,这就是链接

In the code of the complete script to fill the list you need to create an instance of a class ie each object (look at added variable c ):在填写列表的完整脚本代码中,您需要创建一个 class 的实例,即每个 object(查看添加的变量c ):

for s in submission:
#other code...
                c = cChallenge(Id, Difficulty, '', Url, Solved)
                cList.append(c)
#other code...

Don't know exactly what are you trying to put into the list, but probably this will do.不确切知道您要放入列表中的内容,但可能会这样做。

Just like @Alecx note就像@Alecx 注意

to fill the list you need to create an instance of a class要填写列表,您需要创建一个 class 的实例

so the right code for who look inside the pastebin is:因此,在 pastebin 内部查看的正确代码是:

for s in submission
   ...
   _ = cChallenge(...)
   cList.append(_)

I will post the github link to the project tomorrow for who is interested!我将在明天发布 github 链接到该项目,以供有兴趣的人使用!

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

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