装饰器就是为了拓展原来函数或者类功能的一种方法,拓展和被拓展对象能够是函数,也能够是类函数
# -*- 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))
内容是:森林里有个动物. 它是小猫,正在河边钓鱼
系统定义的默认装饰器测试
静态属性,和实例绑定.net
非静态属性示例code
# -*- 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
小猫在河边钓鱼
类方法,和类绑定get
实例化执行示例it
# -*- 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()
小猫在河边钓鱼
类方法非实例化示例io
#-*- coding:utf8 -*- class Text: @classmethod def event(cls,name,action): print("%s在河边%s" % (name,action)) Text.event("小猫","钓鱼")
小猫在河边钓鱼
静态方法,不和实例绑定,不和类绑定for循环
实例化执行示例event
# -*- 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("小猫","钓鱼")
小猫在河边钓鱼
# -*- 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的目的
# -*- 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
小猫在河边钓鱼