1

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?

2
  • if it's just a list of strings and an index, why don't you use a tuple? Commented Dec 27, 2013 at 7:57
  • There's a whole lot more that I'll be doing than I showed here, so I excised most of it for conciseness. Commented Dec 27, 2013 at 8:18

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oops, yes, that was my mistake with the foo versus MyClass. Got a bit confused there. Thanks!
0

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'))

2 Comments

The OP is requesting for an OOP solution.
Indeed, I'm trying to learn how to use OOP properly, and the rest of the code (that I didn't show) does work better from an OOP perspective.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.