python property和setter详解

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

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

其中fgetfsetfdel对应变量操作的读取(get),设置(set)和删除(del)函数。 
property对象<property object>有三个类方法,即settergetterdelete,用于之后设置相应的函数。

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.0
print(t.time)

这样的访问和设置和赋值语句一样非常自然了。

上面的例子中,如果采用property对象的方法而不是用property函数,那么

扫描二维码关注公众号,回复: 2693599 查看本文章
# 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 = value

t = Timer()
t.time = 1.0
print(t.time)

这两个装饰器 
@property装饰器会把成员函数x转换为getter,相当于做了x = property(); x = x.getter(x_get) 
@x.setter装饰器会把成员函数x转换为setter,相当于做了x = x.seter(x_set).

可以看到我们实现了通过属性x来对私有变量_x进行操作。

猜你喜欢

转载自blog.csdn.net/yy19890521/article/details/81298371