在类属性更改时调用 Python 方法 [英] Call Python Method on Class Attribute Change

查看:41
本文介绍了在类属性更改时调用 Python 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 API 解析 Twitter 机器人,我对 OOP 非常陌生.我有一些依赖全局变量的现有 Python 代码,我想我可以借此机会学习.

I'm writing an API parsing Twitter bot and am very new to OOP. I have some existing Python code that relies on global variables and figured I could take this opportunity to learn.

我有以下 Team 类,它会在解析 API 时更新,并且在类属性更改时能够调用完全不相关的(外部)方法.

I have the following Team class that gets updated when the API is parsed and is like to be able to call a totally unrelated (external) method when a class attribute changes.

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 的现有实例时,我希望调用以下方法(伪代码):

When goalie_pulled is changed for an existing instance of Team I'd like the following method to be called (pseudo code):

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 属性发生变化,我如何从我的 Team 类中调用 goalie_pulled_tweet?
  2. 我可以从任何地方访问我的 Game 对象的实例,还是需要将其传递给该变量?
  1. How do I call goalie_pulled_tweet from within my Team class once I detect that goalie_pulled attribute has changed?
  2. Can I access an instance of my Game object from anywhere or does it need to be passed to that variable as well?

推荐答案

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

You should take a look at the property class. Basically, it lets you encapsulate behaviour and private members without the consumer even noticing it.

在您的示例中,您可能有一个 goalie_pulled 属性:

In your example, you may have a goalie_pulled property:

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'

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

I'd recommend you to use properties whenever you can (and must), as they are a nice way of abstraction.

这篇关于在类属性更改时调用 Python 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆