2010-07-28 65 views

回答

2

首先你定義一個類MainString。在__init__方法(構造函數),您所創建的實例變量(Sub1等):

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

然後創建類的實例。您可以更改實例變量的值,該實例:

StringNumberOne = MainString() 
StringNumberOne.Sub1 = "hello" 
2

我在每個這些值的調用不知道我是否理解你的問題。你可以像這樣的班級:

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) 
+1

代碼上述失蹤'def'在'__str__' – bstpierre 2010-07-28 12:30:24

4

還有一個名爲元組的方法:

from collections import namedtuple 

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

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