python decorator 用法

本文详细介绍了Python中的装饰器用法,包括方法装饰器和类装饰器的具体实现方式,并通过实例展示了如何使用装饰器来增强函数和类的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.zhihu.com/question/31265857
http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

方法装饰器
def decorator(Func):
    def new_Func(a, b):
        print 'input:', a, b
        return Func(a, b)
    return new_Func

@decorator
def square_sum(a, b):
    return a**2 + b**2

@decorator
def square_diff(a, b):
    return a**2 - b**2

print square_sum(3, 4)
print square_diff(3, 4)
# output
input:  3 4
25
input:  3 4
-7
类装饰器
def decorator(Class):
    class new_Class:
        def __init__(self, age):
            self.total_display  = 0
            self.wrapped = Class(age)

        def display(self):
            self.total_display += 1
            print("total display", self.total_display)
            self.wrapped.display()

    return new_Class

@decorator
class Bird(object):
    def __init__(self, age):
        self.age = age

    def display(self):
        print("My age is", self.age)

eagleLord = Bird(5)
for i in range(3):
    eagleLord.display()
# output
('total display', 1)
('My age is', 5)
('total display', 2)
('My age is', 5)
('total display', 3)
('My age is', 5)
posted on 2015-08-26 15:04 北京涛子 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liujitao79/p/4760455.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值