The strings are stored on the instance foo
, not the class MyClass
, so you need to for line in foo.a
. Other than that, your solution should work.
An alternative solution would be:
for line in foo.a:
bar.append(MyClass(line, foo.index))
Or, simply using a list comprehension, which seems to me most pythonic here:
bar = [ MyClass(line, foo.index) for line in foo.a ]
(One more thing about your original solution, is that it can potentially be inefficient if foo.a
is huge, because you make a deepcopy
of it, when all you really need is to copy a single line at a time.)
EDIT: to make this answer complete, consider you want to subclass MyClass
, and assign an instance of the subclass to foo
. In this case, using deepcopy
would preserve the type, while instantiating MyClass
explicitly would not. One fix would be to replace MyClass(...)
with type(foo)(...)
.