python装饰器由浅入深_由浅入深,走进Python装饰器-----第五篇:进阶--类装饰类

**类装饰器**

@类

4.1 用类装饰器来扩展原类( 增加属性和方法 )

# 用类装饰器来扩展原函数, 通过对象函数化触发__call__方法,进行返回

class KuoZhan():

def __call__(self,cls):

return self.newfunc(cls)

def good(self):

print("新增的方法!")

def newfunc(self,cls):

def in_newfunc():

cls.addpty = "新增的属性"

cls.good = KuoZhan.good

# 此处返回的是一个实例化对象

return cls()

return in_newfunc

@KuoZhan() #1. KuoZhan() ==> obj 2. @KuoZhan()==> @obj ==> obj( ) 3. @KuoZhan() == obj( MyClass), ,触发__call__ ,得到 in_newfunc

class MyClass():

def func(self):

print("我是原类的方法")

# MyClass实际就是in_newfunc, MyClass() == in_newfunc() , 所以 obj = cls()

# 对象调用方式

obj = MyClass()

obj.func()

obj.good()

print(obj.addpty)

>>>我是原类的方法

>>>新增的方法啦!

>>>新增的属性

4.2 用类装饰器来扩展原类( 增加属性和方法 )

# 用类装饰器来扩展原函数, 直接通过类方法修饰后,进行返回

class KuoZhan():

def good():

print("新增的方法啦!")

def newfunc(cls):

def in_newfunc():

cls.addpty = "新增的属性"

cls.good = KuoZhan.good

# 此处返回的是一个类

return cls

return in_newfunc

# 类.方法 的方式

@KuoZhan.newfunc #1. MyClass = KuoZhan.newfunc(MyClass) ==> MyClass = in_newfunc

class MyClass():

def func():

print("我是原类的方法")

obj = MyClass()

obj.func()

obj.good()

print(obj.addpty)

>>>我是原类的方法

>>>新增的方法啦!

>>>新增的属性

4.3 用类装饰器来扩展原类( 改变属性和方法 )

# 用类装饰器来扩展原函数, 通过对象函数化触发__call__方法,进行返回

class KuoZhan():

def __call__(self,cls):

return self.newfunc(cls)

def func(self):

print("新增的方法!")

def newfunc(self,cls):

def in_newfunc():

cls.addpty = "新增的属性"

cls.func = KuoZhan.func

# 此处将原方法变成属性

cls.func2 = cls.func2(self)

# 此处返回的是一个实例化对象,使用的是绑定对象方法,所以上句代码使用绑定对象方法

return cls()

return in_newfunc

@KuoZhan() #1. KuoZhan() ==> obj 2. @KuoZhan()==> @obj ==> obj( ) 3. @KuoZhan() == obj( MyClass), ,触发__call__ ,得到 in_newfunc

class MyClass():

addpty = "原有的属性"

def func(self):

print("我是原类的方法")

def func2(self):

return "我是原类的方法2"

# MyClass实际就是in_newfunc, MyClass() == in_newfunc() , 所以 obj = cls()

obj = MyClass()

obj.func()

print(obj.addpty)

print(obj.func2)

>>>新增的方法!

>>>新增的属性

>>>我是原类的方法2

4.4 用类装饰器来扩展原类( 改变属性和方法 )

# 用类装饰器来扩展原函数, 通过直接调用类方法,进行返回

class KuoZhan():

def func():

print("新增的方法!")

def newfunc(cls):

def in_newfunc():

cls.addpty = "新增的属性"

cls.func = KuoZhan.func

# 注意直接使用类方法,不用额外参数

cls.func2 = cls.func2()

# 此处返回的是一个类

return cls

return in_newfunc

# 类.方法的方式

@KuoZhan.newfunc #1. MyClass = KuoZhan.newfunc(MyClass) ==> MyClass = in_newfunc

class MyClass():

addpty = "原有的属性"

def func():

print("我是原类的方法")

def func2():

return "我是原类的方法2"

# MyClass实际就是in_newfunc, MyClass() == in_newfunc() , 所以 obj = cls()

obj = MyClass()

obj.func()

print(obj.addpty)

print(obj.func2)

>>>新增的方法!

>>>新增的属性

>>>我是原类的方法2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值