您应该看看属性类。基本上,它使您可以封装行为和私有成员,而消费者甚至不会注意到它。
在您的示例中,您可能具有以下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'