class Person: def __init__(self, name, age): self._name = name self._age = age @property def age(self): return self._age @age.setter def age(self, age): if age < 0: raise ValueError("年龄不能为负数!") self._age = age @property def ...
装饰器 decorator 是 Python 的一种程序设计模式,装饰器本质上是一个 Python 函数或类 (class),它可以让其他函数或类,在不需要做任何代码修改的前提下增加额外功能,装饰器的返回值也是一个函数或类对象,有了装饰器,就可以抽离与函数功能本身无关的代码,放到装饰器中并继续重复使用。 在Python 中,使用「@」作为...
*args, **kws) return new return what_sayerdef FooMaker(word): class Foo(object): @arg_sayer(word) def say(self): pass return Foo()foo1 = FooMaker('this')foo2 = FooMaker('that')print type(foo
在上文中,我们讨论了用于修饰function的装饰器,现在我们来看用于修饰class的装饰器。首先来看一个例子,其中使用了built-in的@property @classmethod @staticmethod。@property常用于设置setter和getter。 classStudent:def__init__(self, name,id): self._name = name self._id=id@propertydefid(self):returnself._...
class my_decorator_class: def __init__(self, func): self.func = func def __call__(self, *args: Any, **kwds: Any) -> Any: print(f'{self.func.__name__}被执行') ret = self.func(*args, **kwds) print(f'{self.func.__name__}执行完毕') ...
refer:浅谈python函数装饰器(wrapper) - 知乎 (zhihu.com) 什么是Python装饰器? 顾名思义,从字面意思就可以理解,它是用来"装饰"Python的工具,使得代码更具有Python简洁的风格。换句话说,它是一种函数的函数,因为装饰器传入的参数就是一个函数,然后通过实现各种功能来对这个函数的功能进行增强。 装饰器其实就是帮...
Python装饰器的作用是使函数包装与方法包装(一个函数,接受函数并返回其增强函数)变得更容易阅读和理解。最初的使用场景是在方法定义的开头能够将其定义为类方法或静态方法。 不使用装饰器的代码如下所示 类方法不用装饰器的写法 class WithoutDecorators:
self.wrapped.display()returnnewClass @decoratorclassBird:def__init__(self, age): self.age=agedefdisplay(self):print("My age is",self.age) eagleLord= Bird(5)foriinrange(3): eagleLord.display() 在decorator中,我们返回了一个新类newClass。在新类中,我们记录了原来类生成的对象(self.wrapped)...
我之前在《理解Python的装饰器(decorators)Part 1》里面讲到过,装饰器可以分为两大类,一种是decorating function装饰函数,还有一种是装饰类decorating class。之前我所用到的例子都是function decorator。这里就讲讲class decorator。与function decorator类似,class decorator也是一个函数(或者可调用对象callable object): ...
class Circle: #半径用下划线开头,表示私有变量 def __init__(self, radius): self._radius = radius #用property装饰器创建虚拟的半径属性 @property def radius(self): return self._radius #用setter装饰器给半径属性添加赋值操作 @radius.setter def radius(self, value): if value >= 0: self._radius...