2 回答

TA贡献1735条经验 获得超5个赞
def getatt(self, number):
return getattr(self, 'att%d' % number)
或采用新的样式格式:
def getatt(self, number):
return getattr(self, 'att{}'.format(number))
还要注意,如果您具有许多这些属性,则可能应该考虑存储列表并从它们的索引中检索元素。

TA贡献1828条经验 获得超3个赞
我会做类似的事情
class My_Class:
def __init__(self):
self.att = {1: 1, 2: 2, 3: 3}
def getatt(self, number):
return self.att[number]
def __getattr__(self, attname):
if attname.startswith('att') and attname != 'att':
try: num = int(attname[3:])
except ValueError: pass
else: return self.att[num]
raise AttributeError(attname)
(未试)
这样,您可以访问捆绑的数据以及必要时的属性。
添加回答
举报