python 中的内置装饰器
@property、@ .setter和@ .deleter的用法:
- @property
- 把属性装饰成get方法
- 给属性赋值时,会自动调用@property装饰的方法
- 只设置属性的@property 时,属性为只读
- @ .setter
- 把属性装饰成set方法
- 给属性赋值时,会自动调用@score.setter装饰的方法
- @.deleter
- 删除的时候调用
两者结合使用如下:
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
@score.deleter
def score(self): # del obj.score 时候调用
print("删除的时候调用")
这样就可以使用了:
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
还有个@ .getter方法
一般用不到,就是调用这个属性的时候会返回什么值。代码如下:
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
@score.getter
def score(self):
return "world"
此时,无论_score的值为多少,或者这个属性的时候返回的值都是world。
@classmethod用法:
这个有个cls。
既可以调用也可以实例化后调用:
class A(object):
bar = 1
def func1(self):
print ('foo')
@classmethod
def func2(cls):
print ('func2')
print (cls.bar)
cls().func1() # 调用 foo 方法
A.func2() # 不需要实例化
输出结果如下:
func2
1
foo
@staticmethod用法:
这个没有cls。
既可以直接调用又可以实例化后调用:
class C(object):
@staticmethod
def f():
print('runoob');
C.f(); # 静态方法无需实例化
cobj = C()
cobj.f() # 也可以实例化后调用
@abstractmethod
用于程序接口的控制,正如上面的特性,含有@abstractmethod修饰的父类不能实例化,但是继承的子类必须实现@abstractmethod装饰的方法。
from abc import abstractmethod
class User(models.Model):
...
@abstractmethod
def get_absolute_url(self):
pass
参考文章
-
廖雪峰:https://www.liaoxuefeng.com/wiki/897692888725344/923030547069856)
-
Python装饰器abstractmethod、property、classmethod、staticmethod及自定义装饰器: https://www.runoob.com/python/python-func-staticmethod.html