栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【装饰器】学习笔记

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【装饰器】学习笔记

python 函数装饰器

简单来说,装饰器的作用是修改其他函数的功能。它其实是一个函数,只是这个函数的输入参数也是函数。你可以简单理解成,当你调用被装饰器装饰的函数时,被装饰的函数仅仅是作为一个传入参数,你实际执行的函数其实是你的装饰器函数。

自定义装饰器

直接上demo

# -*- coding: utf-8 -*-

# 定义一个装饰器,内容是打印函数的返回值
def print_test(func):

    def _print(*args):
        print(f"{func(*args)}")

    return _print


# 使用装饰器装饰函数
@print_test
def decorators(param: str):
    return f"decorators test: print(‘{param}’)"

if __name__ == '__main__':
    decorators("测试自定义装饰器")

执行结果

decorators test: print(‘测试自定义装饰器’)
内置的装饰器

以下是个人平时用得比较多的几个类中的装饰器(其实不用装饰器也完全可以得到想要的结果,只是用上看起来比较装逼)

# -*- coding: utf-8 -*-

class TestClass(object):
    
    note = f"这是类成员"

    @classmethod
    def decorators_classmethod(self):
        print(f"classmethod 使得类无需实例化,即可直接调用,亦可直接调用类成员---{self.note}")
    
    @property
    def decorators_property(self):
        return f"property 创建只读属性,使得方法可以像属性一样被访问(调用时不含括号)"
    
    @staticmethod
    def decorators_staticmethod():
        print(f"staticmethod 表示静态方法,该修饰词的方法无需输入,也不能使用self")



if __name__ == '__main__':
    TestClass.decorators_classmethod()

    test = TestClass()
    print(test.decorators_property)
    test.decorators_staticmethod()

执行结果

classmethod 使得类无需实例化,即可直接调用,亦可直接调用类成员---这是类成员
property 创建只读属性,使得方法可以像属性一样被访问(调用时不含括号)
staticmethod 表示静态方法,该修饰词的方法无需输入,也不能使用self
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/295882.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号