在类属性更改时调用Python方法

发布于 2021-01-29 15:03:30

我正在编写一个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我希望调用以下方法(伪代码):

def goalie_pulled_tweet(team):
  tweet = "{} has pulled their goalie with {} remaining!".format(team.team_name, game.period_remain)
  send_tweet(tweet)

两件事情 -

  1. 一旦检测到属性已更改,如何goalie_pulled_tweetTeam班级内部调用goalie_pulled
  2. 我可以Game从任何地方访问对象的实例,还是也需要将其传递给该变量?
关注者
0
被浏览
84
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您应该看看属性类。基本上,它使您可以封装行为和私有成员,而消费者甚至不会注意到它。

    在您的示例中,您可能具有以下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'
    

    我建议您尽可能(且必须)使用属性,因为它们是一种很好的抽象方法。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看