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

 

相关文章:

  • 2021-06-06
  • 2022-12-23
  • 2021-08-19
  • 2022-12-23
  • 2022-02-26
  • 2022-12-23
  • 2021-07-07
猜你喜欢
  • 2021-10-29
  • 2019-02-11
  • 2022-01-29
  • 2019-11-08
  • 2021-11-14
  • 2021-06-20
  • 2021-08-09
相关资源
相似解决方案