您应该看看属性类。基本上,它使您可以封装行为和私有成员,而消费者甚至不会注意到它。
在您的示例中,您可能具有以下
goalie_pulled属性:
class Team(object): def __init__(self, team_name, tri_pre, goals, shots, goalie_pulled): # Notice the identation here. This is very important. self.team_name = team_name self.tri_pre = tri_pre 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 calledteam.goalie_pulled = 'some_value'
我建议您尽可能(且必须)使用属性,因为它们是一种很好的抽象方法。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)