跳到主要内容

Python 的装饰器

decorator 用起来就像是 Java 的 注解 但是实际更像 Java 的反射,能获取一个函数在其之前执行东西(代理模式)

# 定义一个 装饰器
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper


@log
def now():
print('2015-3-25')


# 例2
def spamrun(fn):
def sayspam(*args):
print("spam,spam,spam")
fn(*args)
return sayspam

@spamrun
def useful(a,b):
print(a*b)

if __name__ == "__main__"
useful(2,5)

# 输出:
# spam,spam,spam
# 10

常用的装饰器

标识静态方法

staticmethod:用来修饰类中的方法,使得该方法可以直接用类名访问

classmethod:和 staticmethod 类似,区别在于 classmethod 会将 class 传入被修饰的方法中。

class A(object):
a = 1
def __init__(self):
self.a = 2

@staticmethod
def foo1():
print(A.a)

@classmethod
def foo2(cls):
print("class a is", cls.a)
print("instance a is", cls().a)


A.foo1()
A.foo2()

# 输出为:
# 1
# class a is 1
# instance a is 2

setter 和 getter

@property 装饰器就是负责把一个方法变成属性调用的(注意访问和赋值的方法名是一样的)

即:把一个 getter 方法变成属性,只需要加上 @property 就可以了,此时,@property 本身又创建了另一个装饰器 @score.setter,负责把一个 setter 方法变成属性赋值

class A(object):
def __init__(self):
self.__count = 0

@property
def count(self):
return self.__count

@count.setter
def count(self, value):
# 检测类型
if not isinstance(value, int):
raise ValueError('count must be an integer!')
self.__count = value


a = A()
print(a.count)
a.count = 1
print(a.count)
a.count = "a" # raise ValueError