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

  • 相关阅读:
    优先队列
    Problem W UVA 662 二十三 Fast Food
    UVA 607 二十二 Scheduling Lectures
    UVA 590 二十一 Always on the run
    UVA 442 二十 Matrix Chain Multiplication
    UVA 437 十九 The Tower of Babylon
    UVA 10254 十八 The Priest Mathematician
    UVA 10453 十七 Make Palindrome
    UVA 10163 十六 Storage Keepers
    UVA 1252 十五 Twenty Questions
  • 原文地址:https://www.cnblogs.com/linwenbin/p/10369940.html
Copyright © 2011-2022 走看看