Python内置装饰器(decorator)解释

@python内置装饰器含义解释

看过了关于python装饰器的博客,受益很大:
https://www.cnblogs.com/cicaday/p/python-decorator.html

装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用。

在此对内置装饰器@property @staticmethod @classmethod查了文档,当前python解释器含有69个内置方法(Built-in Function),property、staticmethod、classmethod即为其中3个。

1.@property

class property(fget=None, fset=None, fdel=None, doc=None)

返回一个property属性,fget/fset/fdel分别是get、set、del函数,doc为属性创建docstring

常见用法是:

class Line(object):
    def __init__(self, start=Point(0, 0), end=Point(0, 0)):
        self._start = start
        self._end = end
        
    @property
    def start(self):
        return self._start
        
    @start.setter
    def start(self, start):
        self._start = start
  • 为什么需要使用getter函数?
    如果不使用,将输出属性所在的内存位置,而不是属性的内容。简而言之,@property相当于创建了getter函数。
  • 为什么先用@property,不需要.getter,后面使用实例化@start.setter?
    property是内置方法(built-in function),使用@property后,其过程相当于进行了property的实例化,返回了一个可调用的对象(callable object),start既是实例化的property也默认为getter函数。即start = property(getx, setx, delx)。property对象含有三个方法:getter、setter、deleter。后续@start.setter是对setter函数的调用。

2.@staticmethod

将一个函数转换为静态函数,返回了一个staticmethod对象,

Can be called either on the class (such as C.f()) or on an instance (such as C().f()).既可以使用类调用(C.f()),也可以实例化调用(C().f())

class C:
@staticmethod
def f(arg1, arg2, ...):
	......

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner

3.@classmethod

将一个函数转变为类函数

class C:
@classmethod
def f(cls, arg1, arg2, …): …

猜你喜欢

转载自blog.csdn.net/houhuipeng/article/details/90751432