python @property @*.setter
在python 代码中有时候可以看到如下片段:
@property
def tick(self):
return self._tick@tick.setter
def tick(self, tick):
self._tick = tick
self.save_netnode()
片段来自于下面的类定义中
class Core(Module):
.............
def __init__(self, plugin):
super(Core, self).__init__(plugin)
self._project = None
self._database = None
self._tick = 0
self._users = {}self._idb_hooks = None
self._idp_hooks = None
self._hxe_hooks = Noneself._idb_hooks_core = None
self._idp_hooks_core = None
self._ui_hooks_core = None
self._view_hooks_core = None
self._hooked = False@property
def project(self):
return self._project@project.setter
def project(self, project):
self._project = project
self.save_netnode()@property
def database(self):
return self._database@database.setter
def database(self, database):
self._database = database
self.save_netnode()@property
def tick(self):
return self._tick@tick.setter
def tick(self, tick):
self._tick = tick
self.save_netnode()
.................................
解读如下:
@property 可以将 python 定义的函数 “当做” 属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。
- 只有 @property 表示只读
- 同时有 @property 和 @*.setter 表示可读可写
- 同时有 @property和 @.setter 和 @.deleter 表示 可读可写可删除
zhangji16@zhangji16vm:/tmp$ cat tmp3.py
#!/usr/bin/env python
# coding=utf-8
class ball(object):def __init__(self, b_id = '001'):
self.__id = b_id@property
def size(self):
print("here here!!!")
return self._size@size.setter
def size(self, b_size):
if type(b_size) != int:
raise ValueError('size should be an integer!')
print("size setted!!!")
self._size = b_size@property
def get_id(self):
return self.__idb = ball('002')
b.size = 20
print b.size
print b.get_id
zhangji16@zhangji16vm:/tmp$ python -i tmp3.py
size setted!!!
here here !!!
20
002
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)
- python青少年编程比赛_第十一届蓝桥杯大赛青少年创意编程组比赛细则
- Python数据分析(一)(Matplotlib使用)
- Python|Python 9.20