栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

在您的示例中,您可能具有以下

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'

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637195.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号