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 = None

        self._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 表示 可读可写可删除

简单 demo 如下

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.__id

b = 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)