您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

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

python 2022/1/1 18:42:14 有430人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶