简介
装饰器就是为了拓展原来函数或者类功能的一种方法,拓展和被拓展对象可以是函数,也可以是类
示例
# -*- coding:utf8 -*-
def deco(obj): #定义类装饰器
'''
这是一个类的装饰器
'''
obj.x = 1
return obj
@deco #语法糖【相当于 deco = deco(foo)】
class Foo:
'''
这是一个测试的类
'''
print(Foo.__dict__) #测试结果,类Foo字典中是否有装饰器中的属性
{'__module__': '__main__', '__doc__': '\n 这是一个测试的类\n ', '__dict__': <attribute '__dict__' of 'Foo' objects>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, 'x': 1}
实例
# -*- coding:utf8 -*-
def Typed(**kwargs): #定义修饰的类
def deco(obj): #定义源类
for key,val in kwargs.items(): #items方法for循环字典中键值对
setattr(obj,key,val) #用setattr方法添加键值对到obj字典中
return obj #返回源类的obj属性
return deco #返回修饰过的类
@Typed(A = '小猫',B = '河边',C = '钓鱼') #装饰器修饰类,加入修饰参数
class Test: #定义的测试类
print("内容是:森林里有个动物.") #测试类中的内容
print("它是%s,正在%s%s" %(Test.A,Test.B,Test.C))
内容是:森林里有个动物.
它是小猫,正在河边钓鱼
系统修饰符
系统定义的默认装饰器
property
静态属性,和实例绑定
非静态属性示例
# -*- coding:utf8 -*-
class Text:
def __init__(self,name,action):
self.Name = name
self.Action = action
def event(self):
print("%s在河边%s" % (self.Name, self.Action))
P = Text("小猫","钓鱼")
P.event()
小猫在河边钓鱼
静态属性示例(封装逻辑)
# -*- coding:utf8 -*-
class Text:
def __init__(self,name,action):
self.Name = name
self.Action = action
@property #相当于 【property = property(event)】
def event(self):
print("%s在河边%s" % (self.Name, self.Action))
P = Text("小猫","钓鱼")
P.event
小猫在河边钓鱼
classmethod
类方法,和类绑定
实例化执行示例
# -*- coding:utf8 -*-
class Text:
def __init__(self,name,action):
self.Name = name
self.Action = action
def event(self):
print("%s在河边%s" % (self.Name,self.Action))
P = Text("小猫","钓鱼")
P.event()
小猫在河边钓鱼
类方法非实例化示例
#-*- coding:utf8 -*-
class Text:
@classmethod
def event(cls,name,action):
print("%s在河边%s" % (name,action))
Text.event("小猫","钓鱼")
小猫在河边钓鱼
staticmethod
静态方法,不和实例绑定,不和类绑定
实例化执行示例
# -*- coding:utf8 -*-
class Text:
def __init__(self,name,action):
self.Name = name
self.Action = action
def event(self):
print("%s在河边%s" % (self.Name,self.Action))
P = Text("小猫","钓鱼")
P.event()
小猫在河边钓鱼
静态方法示例
# -*- coding:utf8 -*-
class Text:
@staticmethod
def event2(name,action):
print("%s在河边%s" % (name,action))
Text.event2("小猫","钓鱼")
小猫在河边钓鱼
扩展
property配合setter方法
# -*- coding:utf8 -*-
class Text:
def __init__(self,name,action):
self.Name = name
self.Action = action
@property #相当于 【property = property(event)】
def event(self): #触发get执行
print("%s在河边%s" % (self.Name,self.Action))
@event.setter #触发set执行
def event(self,val):
print("在%s%s的是一只%s" %(val,self.Action,self.Name))
P = Text("小猫","钓鱼")
P.event
P.event = '海边'
小猫在河边钓鱼
在海边钓鱼的是一只小猫
自制模拟@property
利用描述符达到自制@property的目的
# -*- coding:utf8 -*-
class lazyproperty: #定义模仿property的类
def __init__(self,func): #初始化类
self.func = func
def __get__(self, instance, owner): #定义描述符用于生成类似property方法
res = self.func(instance)
return res
class Text: #原始类
def __init__(self,name,action):
self.Name = name
self.Action = action
@lazyproperty #相当于 【lazyproperty = lazyproperty(event)】
def event(self):
print("%s在河边%s" % (self.Name, self.Action))
P = Text("小猫","钓鱼")
P.event
小猫在河边钓鱼