我的一个类对一组对象进行大量聚合计算,然后分配一个适合特定对象的属性和值:即
class Team(object):
def __init__(self, name): # updated for typo in code, added self
self.name = name
class LeagueDetails(object):
def __init__(self): # added for clarity, corrected another typo
self.team_list = [Team('name'), ...]
self.calculate_league_standings() # added for clarity
def calculate_league_standings(self):
# calculate standings as a team_place_dict
for team in self.team_list:
team.place = team_place_dict[team.name] # a new team attribute
我知道,只要calculate_league_standings
一直运行,每个团队都有team.place
。我想要做的是扫描代码class Team(object)
并读取所有属性,这些属性都是由类方法创建的,也是由对类对象进行操作的外部方法创建的。我有点厌倦了打字for p in dir(team): print p
只是为了看看属性名称是什么。attributes
我可以在 Team 中定义一堆空白__init__
。例如
class Team(object):
def __init__(self, name): # updated for typo in code, added self
self.name = name
self.place = None # dummy attribute, but recognizable when the code is scanned
calculate_league_standings
返回team._place
然后添加似乎是多余的
@property
def place(self): return self._place
我知道我可以在顶部评论属性列表class Team
,这是显而易见的解决方案,但我觉得这里必须有一个最佳实践,这里有一些 Pythonic 和优雅的东西。