Python语法练习_装饰器

Python语法练习

注:大家觉得博客好的话,别忘了点赞收藏呀,本人每周都会更新关于人工智能和大数据相关的内容,内容多为原创,Python Java Scala SQL 代码,CV NLP 推荐系统等,Spark Flink Kafka Hbase Hive Flume等等~写的都是纯干货,各种顶会的论文解读,一起进步。
今天继续和大家分享一下Python语法练习_装饰器
#博学谷IT学习技术支持



前言

装饰器案例


一、装饰器案例

练习1

def verify_permission(func):
    def wrapper(*args, **kwargs):
        print("验证功能")
        func(*args, **kwargs)

    return wrapper


@verify_permission
def deposit(money):
    print(f"存入{money}钱")


@verify_permission
def withdraw(login_id, pwd):
    print("取钱咯", login_id, pwd)


deposit(3000)
withdraw("zs", 123)

练习2

import time

def print_execute_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        func(*args, **kwargs)
        end_time = time.time()
        execute_time = end_time - start_time
        print(execute_time)
    return wrapper

@print_execute_time
def fun01():
    time.sleep(2)
    print("fun01执行完毕")

@print_execute_time
def fun02():
    time.sleep(1)
    print("fun02执行完毕")

# 原函数名称 = 函数装饰器名称(原函数名称)
# fun01 = print_execute_time(fun01)
# fun02 = print_execute_time(fun02)

fun01()
fun02()

练习3

class People:
    def __init__(self):
        self.name = ''
        self.age = 0
        self.__weight = 0
        self.__images = 1

    # @property
    def weight(self):
        return self.__weight

    @property
    def images(self):
        return self.__images


people = People()
print(people.weight())#实例如果要获取类中的私有属性,一般采取这种方式,但是这种当时看起来不统一,因为调用的是方法,容易引起混淆
print(people.images)#采用这种方法形式更加统一,读者一看便知道是调用的某个属性。



总结

装饰器的本质是:
原函数名称 = 函数装饰器名称(原函数名称)
原函数名称 = wrapper
fun01 = print_execute_time(fun01)
fun01 = wrapper

猜你喜欢

转载自blog.csdn.net/weixin_53280379/article/details/129017405
今日推荐