Python中的property, setter装饰器
来源:互联网 发布:归来 知乎 编辑:程序博客网 时间:2024/06/11 13:49
1. 问题提出
python中用”.”操作来访问和改写类的属性成员时,会调用__get__
和__set__
方法,模式情况下,python会查找class.__dict__
字典,对对应值进行操作。比如C.x
会调用C.__get__
访问最终读取C.__dict__[x]
元素。
如果需要读取时对输出结果进行修饰或者对输入进行合法化检查,通常做法是自己写get和set函数,并通过调get和set函数进行读写类成员属性。
例子:
class Timer: def __init__(self, value = 0.0): self.time = value self.unit = 's' def get_time(self): return str(self.time) + ' ' + self.unit def set_time(self, value): if(value < 0): raise ValueError('Time cannot be negetive.') self.time = valuet = Timer()t.set_time(1.0)t.get_time()
但是这样并不美观,那有没有美颜的办法呢?当然!
2. 解决方案
在变量x
前面加下划线_
表示为私有变量_x
,并将变量名x
设为用property
函数返回的对象(property object)。
property函数的声明为
def property(fget = None, fset = None, fdel = None, doc = None) -> <property object>
其中fget
, fset
, fdel
对应变量操作的读取(get),设置(set)和删除(del)函数。
而property
对象<property object>
有三个类方法,即setter
, getter
和delete
,用于之后设置相应的函数。
3.实现效果
在操作类私成员的时候调用__get__
和__set__
方法时,不再采用默认的读取字典的方法,而使用property
中fget
和fset
指定的方法,从而实现了方便的赋值操作。
注意,即使在__init__
函数中调用赋值语句,也使用的是fset
方法。
例子:
class Timer: def __init__(self, value = 0.0): # 1. 将变量加"_",标志这是私有成员 self._time = value self._unit = 's' def get_time(self): return str(self._time) + ' ' + self._unit def set_time(self, value): if(value < 0): raise ValueError('Time cannot be negetive.') self._time = value # 将变量名赋值为包含get和set方法的property对象 time = property(get_time, set_time)t = Timer()t.time = 1.0print(t.time)
这样的访问和设置和赋值语句一样非常自然了。
上面的例子中,如果采用property对象的方法而不是用property函数,那么
# time = property(get_time, set_time)# =========将变成==============>>>time = property()time = time.getter(get_time)time = time.setter(set_time)
4. property装饰器
如果觉得在最后加property
函数这样写类的时候还是不自然,容易忘会写错,那么装饰器可以让类的书写帅到飞起。
例子:
class Timer: def __init__(self, value = 0.0): self._time = value self._unit = 's' # 使用装饰器的时候,需要注意: # 1. 装饰器名,函数名需要一直 # 2. property需要先声明,再写setter,顺序不能倒过来 @property def time(self): return str(self._time) + ' ' + self._unit @time.setter def time(self, value): if(value < 0): raise ValueError('Time cannot be negetive.') self._time = valuet = Timer()t.time = 1.0print(t.time)
这两个装饰器 @property
装饰器会把成员函数x
转换为getter
,相当于做了x = property(); x = x.getter(x_get)
@x.setter
装饰器会把成员函数x
转换为setter
,相当于做了x = x.seter(x_set)
.
可以看到我们实现了通过属性x
来对私有变量_x
进行操作。
参考资料
https://www.programiz.com/python-programming/property
https://docs.python.org/3/library/functions.html?highlight=property#property
http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186781871161bc8d6497004764b398401a401d4cce000
- Python中的property, setter装饰器
- python中的@property装饰器
- Python @property装饰器
- python装饰器--@property
- Python装饰器之 property()
- Python中的property() 函数 和@property 装饰符
- Python中的property() 函数 和@property 装饰符
- python入门(@property,@*.setter)
- python装饰器之staticmethod,classmethod,property
- python装饰器之staticmethod,classmethod,property
- python中@property装饰器的用法
- python装饰器之staticmethod,classmethod,property
- Python 装饰器,@property 以及 Pycaffe.py
- Python 装饰器,@property 以及 Pycaffe.py
- python中@property装饰器的用法
- Python 内置装饰器staticmethod、classmethod、property
- python内部装饰器@classmethod, @staticmethod, @property
- Python中的装饰器
- rbac与auth权限认证的区别
- mybati缓存机制
- Performing stop of activity that is not resumed
- webservice接口调用OA方法
- 设置Activity的启动模式为singleTask接收不到intent的解决方法+启动模式为standard时,onNewIntent未被调用
- Python中的property, setter装饰器
- I
- k-d tree背诵用模板
- 机器学习系列博客
- lintcode——删除链表中的元素
- 简单轮播的实现
- JavaWeb图表插件的小研究
- .h头文件、 .lib库文件、 .dll动态链接库文件的关系
- Orcale对DBUtils不支持模糊查询(Exception:java.sql.SQLException: ORA-00904)的原因与解决