![]() |
List-Elements as instances of a class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: List-Elements as instances of a class (/thread-2568.html) |
List-Elements as instances of a class - BigMan - Mar-25-2017 Hi, in my Python-Script have a class. Based on that class, several instances should be generated. But because I do not know how many instances I need when the code is executed, I want to use a list: Example, how I thought it could work, but it doesn't: class addresses(): ... ... ... for i, item in enumerate(address_liste): address[i] = addresses() ==> I cannot use lists for class-instances??? How to do it right?[/i] RE: List-Elements as instances of a class - ichabod801 - Mar-25-2017 class Address(object): ... addresses = [] for item in address_list: addresses.append(Address(item))I'm assuming address_list is a list of data that goes into the Address class on initialization. You can shorten this to a list comprehension: addresses = [Address(item) for item in address_list] RE: List-Elements as instances of a class - BigMan - Mar-25-2017 it works! Thank you! Thank you! Thank you! Thank you! Thank you! RE: List-Elements as instances of a class - nilamo - Mar-25-2017 You can. But the problem seems like you're not adding items to the list properly. Use [].append() instead of indexing using an index that's out-of-bounds (which I think is how you add new elements in php). |