At last post we’ve known descriptor. Yes, it’s hard to understand but good to know.

@property is a Decorator + Descriptor

In fact @property is a kind of syntactic sugar. To implement getter or setter easier and more elegant.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2018-07-17 23:36:36
# @Author : Simon (simon.xie@codewalker.me)
# @Link : http://www.codewalker.me
# @Version : 1.0.0

import datetime
class CurrentDate(object):
def __get__(self, instance, owner):
return datetime.date.today()
def __set__(self, instance, value):
raise NotImplementedError("Can't change the current date.")

class Example(object):
date = CurrentDate()

e = Example()
print(e.date)
# raise a exception: NotImplementedError: Can't change the current date.
#e.date = datetime.date.today()

class Example2(object):
def __init__(self, name):
self.name = name

@property
def password(self):
raise AttributeError("Cant's get value of password")

@password.setter
def password(self, password):
self.password_hash = password

e2 = Example2('Alice')
e2.password = 'your_password'
#print(e2.password) #AttributeError: Cant's get value of password

Think about those two ways to get/set variable by some conditions.

Notice:

Once a func was decorated by @property. it becomes a value setter.

I love this world, Good night <3

EOF.