zoukankan      html  css  js  c++  java
  • Python 如何定义只读属性?【新手必学】

     

    在Java里, 若要为一个类定义只读的属性, 只需要将目标属性用private修饰, 然后只提供getter()而不提供setter(). 但Python没有private关键字, 如何定义只读属性呢? 有两种方法, 第一种跟Java类似, 通过定义私有属性实现. 第二种是通过__setattr__.

    通过私有属性

    用私有属性+@property定义只读属性, 需要预先定义好属性名, 然后实现对应的getter方法.,如果对属性还不懂。那建议你先去小编的Python学习.裙 :一久武其而而流一思(数字的谐音)转换下可以找到了,里面有最新Python教程项目,先系统学习下!

    class Vector2D(object):
        def __init__(self, x, y):
            self.__x = float(x)
            self.__y = float(y)
    
        @property
        def x(self):
            return self.__x
        @property
        def y(self):
            return self.__y
    
    if __name__ == "__main__":
        v = Vector2D(3, 4)
        print(v.x, v.y)
        v.x = 8 # error will be raised.

    输出:

    (3.0, 4.0)
    Traceback (most recent call last):
      File ...., line 16, in <module>
        v.x = 8 # error will be raised.
    AttributeError: can't set attribute

    可以看出, 属性x是可读但不可写的.

    通过__setattr__

    当我们调用obj.attr=value时发生了什么?

    很简单, 调用了obj__setattr__方法. 可通过以下代码验证:

    class MyCls():
        def __init__(self):
            pass
    
        def __setattr__(self, f, v):
            print 'setting %r = %r'%(f, v)
    if __name__ == '__main__':
        obj = MyCls()
        obj.new_field = 1

    输出:

    setting 'new_field' = 1
    • 1

    所以呢, 只需要在__setattr__ 方法里挡一下, 就可以阻止属性值的设置, 可谓是釜底抽薪. 
    代码:

    # encoding=utf8
    class MyCls(object):
        readonly_property = 'readonly_property' 
        def __init__(self):
            pass
        def __setattr__(self, f, v):
            if f == 'readonly_property':
                raise AttributeError('{}.{} is READ ONLY'.
                                     format(type(self).__name__, f))
    
            else:
                self.__dict__[f] = v
    
    if __name__ == '__main__':
        obj = MyCls()
    
        obj.any_other_property = 'any_other_property'
        print(obj.any_other_property)
    
        print(obj.readonly_property)
        obj.readonly_property = 1

    输出:

    any_other_property
    readonly_property
    Traceback (most recent call last):
      File "...", line 21, in <module>
        obj.readonly_property = 1
        ...
      AttributeError: MyCls.readonly_property is READ ONL
  • 相关阅读:
    Linux下解析域名命令-dig 命令使用详解
    重写、覆盖、重载、多态几个概念的区别分析
    介绍python中运算符优先级
    介绍Python中6个序列的内置类型
    Mysql(Mariadb)数据库主从复制
    winscp中使用sudo的方法
    git push跳过用户名和密码认证配置教程
    案例:通过shell脚本实现mysql数据备份与清理
    毕业季,我的Linux求职之路
    PHP和ajax详解
  • 原文地址:https://www.cnblogs.com/chengxuyuanaa/p/11987041.html
Copyright © 2011-2022 走看看