python - creating managed attributes
天蓬老师
天蓬老师 2017-04-17 14:20:41
[Python讨论组]

Cookbook 8.6节有个例子:
http://chimera.labs.oreilly.com/books/1230000000393/ch08.html#_problem_124

class Person:
    def __init__(self, first_name):
        self.first_name = first_name

    # Getter function
    @property
    def first_name(self):
        return self._first_name

    # Setter function
    @first_name.setter
    def first_name(self, value):
        if not isinstance(value, str):
            raise TypeError('Expected a string')
        self._first_name = value

    # Deleter function (optional)
    @first_name.deleter
    def first_name(self):
        raise AttributeError("Can't delete attribute")

有个问题是,为什么__init__里面的是self.first_name而不是self._first_name,他说是

In this example, the entire point of the property is to apply type checking when setting an attribute. Thus, chances are you would also want such checking to take place during initialization. By setting self.first_name, the set operation uses the setter method (as opposed to bypassing it by accessing self._first_name).

我看不明白,求解释一下,多谢

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(2)
阿神

__init__里进行初始化 来给first_name赋值
这里使用的self.first_name 是因为要使用
@first_name.setter def first_name(self, value):

如果直接使用self._first_name 那么就不会进入
@first_name.setter def first_name(self, value):

也就没有
if not isinstance(value, str): raise TypeError('Expected a string')
的类型检查。

天蓬老师

和java通过getter访问私有变量类似,避免直接访问变量,更规范

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号