Python常用装饰器有哪些
装饰器是Python中一种非常实用的编程技巧,它允许我们在不修改原函数代码的情况下,为函数添加新的功能,装饰器本质上是一个接受函数作为参数的高阶函数,它可以在不改变原函数的基础上,对原函数进行扩展,本文将介绍一些常用的Python装饰器,以及它们的用法和特点。
内置装饰器
1、@staticmethod
@staticmethod是一个静态方法装饰器,用于将一个方法声明为静态方法,静态方法不需要实例化对象,可以直接通过类名调用,静态方法不需要传入self参数,因此不能访问类的属性和实例的属性。
示例:
class MyClass: @staticmethod def my_static_method(): print("This is a static method.") MyClass.my_static_method()
2、@classmethod
@classmethod是一个类方法装饰器,用于将一个方法声明为类方法,类方法可以通过类名或实例调用,但只能访问类的属性,不能访问实例的属性,类方法的第一个参数通常是cls,表示类本身。
示例:
class MyClass: @classmethod def my_class_method(cls): print("This is a class method.") MyClass.my_class_method() obj = MyClass() obj.my_class_method()
3、@property
@property是一个属性装饰器,用于将一个方法转换为属性,使用@property装饰的方法可以像访问属性一样访问,而不需要加括号调用,可以使用@属性名.setter装饰器定义一个setter方法,用于设置属性值。
示例:
class MyClass: def __init__(self, x): self._x = x @property def x(self): print("Getting 'x' property.") return self._x @x.setter def x(self, value): print("Setting 'x' property to", value) self._x = value obj = MyClass(10) print(obj.x) 获取属性值,输出:Getting 'x' property. 10 obj.x = 20 设置属性值,输出:Setting 'x' property to 20 print(obj.x) 获取属性值,输出:Getting 'x' property. 20
4、@absentdefaultdict、@collections.abc.abstractmethod、@functools.lru_cache等其他内置装饰器,具体用法可以参考Python官方文档。
第三方库装饰器
1、functools.wraps(decorator)
functools.wraps是Python标准库functools中的一个装饰器,用于在定义装饰器时保留被装饰函数的元信息(如函数名、文档字符串等),这对于在使用装饰器生成新函数时保持代码可读性非常重要,使用示例:
import functools from functools import wraps from flask import Flask, request, jsonify, g, redirect, url_for, abort, session as session_modifier, flash as flash_modifier, make_response as make_response_modifier, Response as Response_modifier, copy as copy_modifier, deepcopy as deepcopy_modifier, escape as escape_modifier, getpass as getpass_modifier, hmac as hmac_modifier, Markup as Markup_modifier, unescape as unescape_modifier, url_safe as url_safe_modifier, current_app as current_app_modifier, _request_ctx_stack as request_ctx_stack_modifier, _session_store as session_store_modifier, _secure_filename as secure_filename_modifier, _get_converter as get_converter_modifier, _tojson as tojson_modifier, _tobytes as tobytes_modifier, _tolist as tolist_modifier, _toint as toint_modifier, _tofloat as tofloat_modifier, _tostr as tostr_modifier, _tobinary as tobinary_modifier, _tounicode as tounicode_modifier, _tolistitem as tolistitem_modifier, _tolisttuple as tolisttuple_modifier, _tosetitem as tosetitem_modifier, _tosettuple as tosettuple_modifier, _todictitem as todictitem_modifier, _todicttuple as todicttuple_modifier, _tofrozensetitem as tofrozensetitem_modifier, _tofrozensettuple as tofrozensettuple_modifier, _toenumitem as toenumitem_modifier, _toenumtuple as toenumtuple_modifier, _totextfileobject as totextfileobject_modifier, _makeresponse as makeresponse_modifier, _makestatus as makestatus_modifier, _makeheaders as makeheaders_modifier, _iterencode as iterencode_modifier, _iterdecode as iterdecode_modifier, _unquote as unquote_modifier, _unquoteslashes as unquoteslashes_modifier, _urlparse as urlparse_modifier, _urlunparse as urlunparse_modifier, _urljoin as urljoin_modifier, _urlsplit as urlsplit_modifier, _urlunsplit as urlunsplit_modifier, _quote as quote_modifier, _quoteslashes as quoteslashes_modifier, _unquoteslashes as unquoteslashes_modifier, _unquotepathquerycomponentasstring as unquotepathquerycomponentasstring_modifier, _unquotepathhierarchysegmentasstring as unquotepathhierarchysegmentasstring_modifier; reload(sys)" + " sys.modules['flask'] = sys.modules['flask'].__loader__().load_module(*sys.modules['flask'].__name__)" + " sys.modules['flask'].update(__import__('flask').extensions)" + " sys.modules['flask'].update(__import__('flask').globals())" + " sys.modules['flask'].update(__import__('flask').blueprints)" + " sys.modules['flask'].update(__import__('flask').currentapp)" + " sys.path[-1] = os.path.abspath(os.path.dirname(__file__))" + " sys.path[-1] = os.path.abspath(os.path.dirname(__file__))" + " sys.path[-1] = os.path.abspath(os
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/218180.html