我正在编写一个解析 Twitter 机器人的 API,并且对 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
Run Code Online (Sandbox Code Playgroud)
当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)
Run Code Online (Sandbox Code Playgroud)
两件事情 -
goalie_pulled_tweet从我的班级中调用?Teamgoalie_pulledGame还是也需要将其传递给该变量?Mat*_*ero 12
您应该看一下属性类别。基本上,它可以让您封装行为和私有成员,而消费者甚至不会注意到它。
在您的示例中,您可能有一个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
Run Code Online (Sandbox Code Playgroud)
从消费者的角度来看:
team = create_team_instance()
# goalie_pulled_tweet is called
team.goalie_pulled = 'some_value'
Run Code Online (Sandbox Code Playgroud)
我建议您尽可能(并且必须)使用属性,因为它们是一种很好的抽象方式。