views:

45

answers:

3

How would one do something like this in python

Mainstring:
     Sub1
     Sub2
     Sub3

then call upon each of those values by defining a Mainstring StringNumberOne and

StringNumberOne.Sub1 = ""
+2  A: 

I'm not sure if I understand your question. You can habe a class like this:

class ManySubs(object): # explicit inheritance not needed in 3.x
    def __init__(self, *subs):
        self._subs = subs
        # add sub1..subN fields, but only because you asked for it
        # I think a dynamic fields are an especially bad idea
        # plus, about everytime you have x1..xN, you actually want an array/list
        for i in range(len(subs)):
            setattr(self, 'sub'+str(i+1), subs[i])

    # wrapping code for sequencemethods (__len__, __getitem__, etc)

    def __str__(self):
        return ''.join(self._subs)
delnan
code above missing `def` at `__str__`
bstpierre
+2  A: 

First you define a class MainString. In the __init__ method (the constructor), you create the instance variables (Sub1, etc):

class MainString(object):
    def __init__(self):
        self.Sub1 = ""
        self.Sub2 = ""
        self.Sub3 = ""

Then you create an instance of the class. You can change the value of instance variables for that instance:

StringNumberOne = MainString()
StringNumberOne.Sub1 = "hello"
ars
+4  A: 

There is also the named tuple approach:

from collections import namedtuple

Mainstring = namedtuple('Mainstring', 'sub1 sub2 sub3')

example = Mainstring("a", "b", "c")
print example.sub1  # "a"
EOL