Frage

I need to write a class that takes some raw strings, and then separates them into a list which it holds as attributes. (Among other things, but that's the part I'm concerned with right now.) Something like this:

class MyClass(object):
    def __init__(self, raw, index):
        self.a = raw.split("\n")
        self.index = index

So an instance of MyClass will have an attribute .a, that is a list containing lines from the raw string I initialize the object with, as well as an attribute .index that is the index that I give it, correct? However, I would also like to be able to generate additional instances of MyClass that contain only one line of the raw text each, but possessing the same index.

What I am currently thinking of is this:

from copy import deepcopy
foo = MyClass("lots of text", 1)
bar = []
for line in foo.a:
    copy = deepcopy(MyClass)
    copy.a = line
    bar.append(copy)

Is this the correct way to go about doing this?

War es hilfreich?

Lösung

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)(...).

Andere Tipps

From a non OOP perspective, you can simple use a tuple and you get the same bar values.

from copy import deepcopy
foo = ('lots of text', 1)
bar = deepcopy(foo[0].split('\n'))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top