我正在编写一个API解析Twitter机器人,对OOP来说是个新手。我有一些依赖于全局变量的现有Python代码,并认为我可以借此机会学习。
我有以下Team类,这些类在解析API时会更新,并且希望在类属性更改时能够调用完全不相关的(外部)方法。
class Team(object): def __init__(self, team_name, tri_code, goals, shots, goalie_pulled): self.team_name = team_name self.tri_code = tri_code self.goals = goals self.shots = shots self.goalie_pulled = goalie_pulled
goalie_pulled对于现有实例,何时更改,Team我希望调用以下方法(伪代码):
goalie_pulled
Team
def goalie_pulled_tweet(team): tweet = "{} has pulled their goalie with {} remaining!".format(team.team_name, game.period_remain) send_tweet(tweet)
两件事情 -
goalie_pulled_tweet
Game
您应该看看属性类。基本上,它使您可以封装行为和私有成员,而消费者甚至不会注意到它。
在您的示例中,您可能具有以下goalie_pulled属性:
class Team(object): def __init__(self, team_name, tri_code, goals, shots, goalie_pulled): # Notice the identation here. This is very important. self.team_name = team_name self.tri_code = tri_code self.goals = goals self.shots = shots # Prefix your field with an underscore, this is Python standard way for defining private members self._goalie_pulled = goalie_pulled @property def goalie_pulled(self): return self._goalie_pulled @goalie_pulled.setter def goalie_pulled(self, new_value): self._goalie_pulled = new_value goalie_pulled_tweet(self) #self is the current Team instance
从消费者的角度来看:
team = create_team_instance() # goalie_pulled_tweet is called team.goalie_pulled = 'some_value'
我建议您尽可能(且必须)使用属性,因为它们是一种很好的抽象方法。