zoukankan      html  css  js  c++  java
  • python装饰器@property

    @property可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。
    1、只有@property表示只读。
    2、同时有@property和@*.setter表示可读可写。

    3、同时有@property和@*.setter和@*.deleter表示可读可写可删除。

    class A(object):  # 要求继承object
    def __init__(self):
    self.__name = None

    # 下面开始定义属性,3个函数的名字要一样!
    @property # 读
    def name(self):
    return self.__name

    @name.setter # 写
    def name(self, value):
    self.__name = value

    @name.deleter # 删除
    def name(self):
    del self.__name


    a = A()
    print(a.name ) # 读
    a.name = 'python' # 写
    print(a.name ) # 读
    del a.name # 删除
    print(a.name) # a.name已经被删除 AttributeError: 'A' object has no attribute '_A__name'

    运行结果:

    F:devpythonpython.exe F:/pyCharm/practice/config_dir/property_demo2.py
    None
    Traceback (most recent call last):
    python
    File "F:/pyCharm/practice/config_dir/property_demo2.py", line 24, in <module>
    print(a.name) # a.name已经被删除 AttributeError: 'A' object has no attribute '_A__name'
    File "F:/pyCharm/practice/config_dir/property_demo2.py", line 8, in name
    return self.__name
    AttributeError: 'A' object has no attribute '_A__name'

    Process finished with exit code 1

  • 相关阅读:
    java内部类
    navicat使用教程-PJ
    提交代码时的注意事项
    多线程技术
    Apache POI使用详解
    网站链接收藏夹
    MySQL优化
    Oracle创建用户、角色、授权、建表
    oracle 安装提示未找到文件安装
    Json对象与Json字符串的转化、JSON字符串与Java对象的转换
  • 原文地址:https://www.cnblogs.com/linwenbin/p/10369940.html
Copyright © 2011-2022 走看看