python中面向切片编程(AOP)和装饰器

it2026-08-30  14

@函数名(类的描述符)相当于fuc = decorator(fuc)

装饰器:

def deco(fuc): print('============') return fuc @deco def foo(): print('foo函数正在运行') foo()

  

利用描述符自定制property

class Decorator: def __init__(self, fuc): self.fuc = fuc def __get__(self, instance, owner): print('这里是get') return self.fuc(instance) class Room: def __init__(self, width, length): self.length = length self.width = width @Decorator# area = Decorator(area) def area(self): print('执行了area函数') return self.length*self.width room = Room(1,2) print(room.area)

内置的装饰器

内置的装饰器有三个,分别是staticmethod、classmethod和property,作用分别是把类中定义的实例方法变成静态方法、类方法和类属性。由于模块里可以定义函数,所以静态方法和类方法的用处并不是太多,除非你想要完全的面向对象编程。而属性也不是不可或缺的,Java没有属性也一样活得很滋润。从我个人的Python经验来看,我没有使用过property,使用staticmethod和classmethod的频率也非常低。

 

转载于:https://www.cnblogs.com/CK85/p/10292335.html

最新回复(0)