There is a class:

class signal: lst = [] booklist = None data = [[0, 'nickname' , "nickname"], [1, 'name' , "notempty"]] def __init__(self, row, nrow): for key in self.data: if signal.check(row[key[0]], key[2], "Лист: " + self.booklist + " Строка: " + str(nrow)): setattr(self, key[1], row[key[0]]) 

Class objects I want to store in the list lst. Why create them in this way in the main body of the program:

 signal.lst.append(signal(row, rownum)) 

That somehow it hurts the eye a little. Therefore, when creating an object, I want to save it in lst immediately in the constructor.

I tried to use a decorator

 @classmethod def __init__(cls, self, row, nrow): ... cls.lst.append(self) 

But in the main body of the program:

 signal(row, rownum) 

Then the interpreter scolded me like this:

 TypeError: __init__() missing 1 required positional argument: 'nrow' 

Is there any elegant solution?

  • And if it were not the signal(row, rownum) but the signal(row, nrow) that was written, then would it also signal(row, nrow) ? - LamerXaKer
  • Yes, I would also swear. - AND

1 answer 1

You can refer to lst via self self.lst.append (self)

should work. The following code itself

 class Signal: lst = [] booklist = None data = [[0, 'nickname' , "nickname"], [1, 'name' , "notempty"]] def __init__(self, row, nrow): for key in self.data: setattr(self, key[1], row[key[0]]) self.lst.append(self) if __name__ == '__main__': s = Signal([1, 2], ['name']) print(s.lst) s2 = Signal([2, 5], ['nickname']) print(s.lst) print(s2.lst) print(s.lst == s2.lst, s.lst is s2.lst) 

Gives out

 [<__main__.Signal object at 0x000000616773D080>] [<__main__.Signal object at 0x000000616773D080>, <__main__.Signal object at 0x000000616773D128>] [<__main__.Signal object at 0x000000616773D080>, <__main__.Signal object at 0x000000616773D128>] True True 

What corresponds to the expected.

  • Hmm, I did not think that the object has access to a static class property. - AND