Creating alot of class instances?
Tim Chase
python.list at tim.thechases.com
Sun Jul 5 15:21:35 EDT 2009
> The solution might be dead simple but I just cannot figure out at the
> moment.
>
> For example this is what I need in the simplest form
>
> class myclass():
> def __init__(self,name):
> self.name=name
>
> for count,data in enumerate(some list):
> instance_count=myclass()
> instance_count.name=data
>
> print instances
Sounds like a use for a list:
instances = []
for count, data in enumerate(some_list):
# 1) camel-case is preferred for classnames
# 2) since your __init__() expects the name
# pass it in, instead of setting it later
instance = MyClass(data)
instances.append(instance)
This can be written in a slightly more condensed-yet-readable
list-comprehension form as:
instances = [MyClass(data) for data in some_list]
You then have a list/array of instances you can print:
print instances
or pick off certain items from it:
print instances[42]
-tkc
More information about the Python-list
mailing list