如何在python中执行类似的操作
Mainstring:
Sub1
Sub2
Sub3
然后通过定义Mainstring StringNumberOne
来调用每个值
和
StringNumberOne.Sub1 = ""
答案 0 :(得分:4)
还有一个名为元组的方法:
from collections import namedtuple
Mainstring = namedtuple('Mainstring', 'sub1 sub2 sub3')
example = Mainstring("a", "b", "c")
print example.sub1 # "a"
答案 1 :(得分: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)
答案 2 :(得分:2)
首先定义一个类MainString
。在__init__
方法(构造函数)中,您创建实例变量(Sub1
等):
class MainString(object):
def __init__(self):
self.Sub1 = ""
self.Sub2 = ""
self.Sub3 = ""
然后您创建该类的实例。您可以更改该实例的实例变量的值:
StringNumberOne = MainString()
StringNumberOne.Sub1 = "hello"