zoukankan      html  css  js  c++  java
  • Python的property装饰器的基本用法

          Python的@property装饰器用来把一个类的方法变成类的属性调用,然后@property本身又创建了另一个装饰器,用一个方法给属性赋值。下面是在类中使用了@property后,设置类的读写属性,只读和只写属性。

      all方法设置的是读写属性,可以设置这个属性,也可以读取这个属性,如28行所示,如果没有定义__init__()方法的话,只能首先设置了这个属性才能使用这个属性。在32行中,如果想知道write属性的值,也是会报错的。而在34行中,也是没有办法继续给readonly这个制度属性赋值的。这里使用了@property之后,可以实现Python“私有变量”,当然不是真正的私有,真正的私有比较复杂,不过也可以通过@property实现?在之后学习了再写。

     1 class UseProperty(object):
     2 
     3     def __init__(self):
     4         self._all = 233
     5 
     6     @property
     7     def all(self):
     8         return self._all
     9 
    10     @all.setter
    11     def all(self, v):
    12         self._all = v
    13 
    14     @property
    15     def readonly(self):
    16         return self._all
    17 
    18     @property
    19     def write(self):
    20         raise AttributeError('This is not a readonly attribute.')
    21 
    22     @write.setter
    23     def write(self, value):
    24         self._write = value
    25 
    26 
    27 p = UseProperty()
    28 print p.all
    29 p.all = 100
    30 print p.all
    31 p.write = 233
    32 # print p.write
    33 print p.readonly
    34 # p.readonly = 10
  • 相关阅读:
    cf-779E (拆位)
    石子游戏 (SG函数)
    [POI2017] Flappy Bird (思维题)
    Alice and Bob (SG函数)
    Red is good (DP)
    CodeVS-1669 (背包问题)
    GalaxyOJ-468 (LCA)
    BZOJ-1191 (二分图匹配)
    Reinforcement Learning 笔记(4)
    Reinforcement Learning 笔记(3)
  • 原文地址:https://www.cnblogs.com/qiaojushuang/p/6433209.html
Copyright © 2011-2022 走看看