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, getterdelete,用于之后设置相应的函数。

3.实现效果

在操作类私成员的时候调用__get____set__方法时,不再采用默认的读取字典的方法,而使用propertyfgetfset指定的方法,从而实现了方便的赋值操作。
注意,即使在__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

0 0
原创粉丝点击