1:enter and exit:
1 class Foo: 2 def __init__(self,name): 3 self.name = name 4 5 def __enter__(self): 6 print('execute enter') 7 return self #self to f below 8 9 def __exit__(self, exc_type, exc_val, exc_tb): #the exit sentance over means the whole with sentence over! 10 print('execute exit') 11 print(exc_type) 12 print(exc_val) 13 print(exc_tb) 14 return True #swallow the wrong reports 15 16 with Foo('a.txt') as f: #f = obj.__enter()__ 17 print(f) ##<__main__.Foo object at 0x0000000001DC7A60> 18 print(sfsddsgfdgfdgdsfgsdf) 19 print(f.name) #a.txt 20 # print('========>') 21 # print('========>') 22 # print('========>') 23 # print('========>') 24 # print('========>') 25 26 print('000000000000000000000000') 27 28 # the result: 29 # execute enter 30 # ========> 31 # ========> 32 # ========> 33 # ========> 34 # ========> 35 # execute exit 36 # 000000000000000000000000
2:The use of decorator:
1 #==============>>>>>>>>>data descriptor: 2 class Typed: 3 def __init__(self,key,expected_type): 4 self.key = key 5 self.expected_type = expected_type 6 7 def __get__(self, instance, owner): 8 # print('get function') 9 # print('instance parameter[%s]' %instance) 10 # print('owner parameter [%s]' %owner) 11 return instance.__dict__[self.key] 12 13 def __set__(self, instance, value): 14 # print('set function') 15 # print('instance parameter[%s]' %instance) 16 # print('owner parameter [%s]' %value) 17 # print('=====>>',self) =====>> <__main__.Typed object at 0x0000000002447A60> 18 if not isinstance(value,self.expected_type): 19 # print('please insert a string type') 20 raise TypeError('%s is not the Type %s' %(self.key,self.expected_type)) 21 instance.__dict__[self.key] = value 22 23 def __delete__(self, instance): 24 return instance.__dict__.pop(self.key) 25 26 class People: 27 name = Typed('name',str) #trigure __set__() 28 age = Typed('age',int) 29 salary = Typed('salary',float) 30 gender = Typed('gender',str) 31 def __init__(self,name,age,salary,gender): 32 self.name = name 33 self.age = age 34 self.salary = salary 35 self.gender = gender 36 37 38 # p1 = People('zxver',18,33.3) 39 # print(p1.__dict__) 40 p1 = People('zxver',453,234) 41 # print(p1.__dict__) 42 # p1.name 43 # print(p1.name) 44 # p1.name = 'egon' 45 # print(p1.__dict__) 46 # del p1.name 47 # print(p1.__dict__) 48 #{'age': 18, 'salary': 33.3} 49 #because the age is agented by the data descriptor which is higher level than object 50 51 52 #the refined one: 53 class Typed: 54 def __init__(self,key,expected_type): 55 self.key = key 56 self.expected_type = expected_type 57 58 def __get__(self, instance, owner): 59 # print('get function') 60 # print('instance parameter[%s]' %instance) #p1 61 # print('owner parameter [%s]' %owner) #People 62 return instance.__dict__[self.key] 63 64 def __set__(self, instance, value): 65 # print('set function') 66 # print('instance parameter[%s]' %instance) 67 # print('owner parameter [%s]' %value) 68 # print('=====>>',self) =====>> <__main__.Typed object at 0x0000000002447A60> 69 if not isinstance(value,self.expected_type): 70 # print('please insert a string type') 71 raise TypeError('%s is not the Type %s' %(self.key,self.expected_type)) 72 instance.__dict__[self.key] = value 73 74 def __delete__(self, instance): 75 return instance.__dict__.pop(self.key) 76 77 def deco(**kwargs): 78 def wrapper(obj): 79 for key,val in kwargs.items(): 80 # obj.__dict__[key]=val 81 setattr(obj,key,Typed(key,val)) 82 return obj 83 return wrapper 84 85 # @deco(name=Typed('name',str),age = Typed('age',int),salary = Typed('salary',float),gender = Typed('gender',str)) 86 @deco(name=str,age=int,salary=float,gender=str)#can add the content which you need 87 class People: 88 # name = Typed('name',str) #trigure __set__() 89 # age = Typed('age',int) 90 # salary = Typed('salary',float) 91 # gender = Typed('gender',str) 92 def __init__(self,name,age,salary,gender): 93 self.name = name 94 self.age = age 95 self.salary = salary 96 self.gender = gender 97 98 99 # p1 = People('zxver',18,33.3) 100 # print(p1.__dict__) 101 p1 = People('zxver',18,13.7,'male') 102 print(p1.__dict__) 103 print(People.__dict__)
3:Class_decorator:
1 # def deco(func): 2 # print('=======') 3 # return func 4 # 5 # # @deco #test = deco(test) 6 # # def test(): 7 # # print('test is executing') 8 # 9 # # test() 10 # 11 # @deco #Foo = deco(Foo) 12 # class Foo: 13 # pass 14 # 15 # f1 = Foo() 16 # print(f1) 17 18 def deco(obj): 19 print('=======',obj) 20 obj.x = 1 21 obj.y = 2 22 obj.z = 3 23 return obj 24 25 @deco #Foo = deco(Foo) 26 class Foo: 27 pass 28 29 print(Foo.__dict__) 30 31 #>>>>>>>>>>>>>>.all is object: 32 @deco 33 def test(): 34 print('test function') 35 print(test.__dict__) 36 37 38 ################ 39 40 def Typed(**kwargs): 41 def deco(obj): 42 print('=====>',kwargs) 43 print('=====>',obj) 44 for key,val in kwargs.items(): 45 # obj.__dict__[key]=val 46 setattr(obj,key,val) 47 # obj.x = 1 48 # obj.y = 1 49 # obj.z = 1 50 return obj 51 print('===>',kwargs) 52 return deco 53 54 @Typed(x=1,y=2,z=3) #it will execute with () 1.Typed(x=1,y=2,z=3) --->deco 2.@deco --->Foo=deco(Foo) 55 class Foo: 56 pass 57 print(Foo.__dict__) 58 59 @Typed(name='zxver') #Bar = deco(Bar) 60 class Bar: 61 pass 62 print(Bar.__dict__) 63 print(Bar.name)
4:Property:
1 class Lazyproperty: 2 def __init__(self,func): 3 print('=======>>') 4 self.func = func 5 6 def __get__(self, instance, owner): 7 if instance is None: 8 return self 9 res = self.func(instance) 10 setattr(instance,self.func.__name__,res) 11 return res 12 13 # def __set__(self, instance, value): 14 # pass 15 16 ##*****************:important:if add __set__attribute ,the set priviledge will be higher ,then when you call tha r1.area, 17 ##it can't ectract the content from r1. 18 19 class Room: 20 def __init__(self,name,width,length): 21 self.name = name 22 self.width = width 23 self.length = length 24 25 # @property #area = property(area) 26 @Lazyproperty #area = Lazyproperty(area) #execute Lazyproperty's _init__function 27 def area(self): 28 return self.width * self.length 29 30 @property 31 def area1(self): 32 return self.width * self.length 33 @property 34 def test(self): 35 # print('------') 36 return '11111111111111' 37 38 r1 = Room('restroom',1,1) 39 ########instance call: 40 # print(r1.area1) #execute __get__() 41 # print(r1.area1) #execute __get__() 42 # print(r1.area1) #execute __get__() 43 44 print(r1.area) #execute __get__() 45 print(r1.__dict__) ##extract from the r1 46 print(r1.area) ##extract from the r1 47 48 ########class call: 49 # print(Room.area) #add a condition to judge the instance is None,return self,or it will report wrong. 50 #result:<__main__.Lazyproperty object at 0x0000000001DD7A60> 51 52 # r1 = Room('restroom',1,1) 53 # print(r1.area.func(r1)) 54 # print(Room.__dict__) 55 # print(r1.test) 56 # print(Room.test) 57 #redult:<property object at 0x0000000001E2A0E0>
5:Metaclass:
1 # class Foo: 2 # pass 3 # 4 # f1 = Foo() 5 # 6 # print(type(f1)) 7 # print(type(Foo)) 8 #the result: 9 # <class '__main__.Foo'> 10 # <class 'type'> 11 12 #the two method to make class: 13 ###########1: 14 # class Foo: 15 # pass 16 # print(Foo) 17 18 ##########2: 19 def __init__(self,name,age): 20 self.name = name 21 self.age = age 22 23 def test(self): 24 print('=====>') 25 26 FFo = type('FFo',(object,),{'x':1,'__init__':__init__,'test':test}) #type(name,father level,attribute) 27 print(FFo) 28 print(FFo.__dict__) 29 f1 = FFo('alex',19) 30 print(f1.x) 31 print(f1.test) 32 f1.test() 33 34 #####make own metaclass: 35 36 class MyType(type): 37 def __init__(self,a,b,c): 38 # print(a) 39 # print(b) 40 # print(c) 41 42 #:Foo 43 # () 44 # {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000000001E0D0D0>} 45 print('made metaclass') 46 47 def __call__(self, *args, **kwargs): 48 print('=======>') 49 print(self) 50 print(args,kwargs) 51 obj = object.__new__(self) #create a new object;object.__new__(Foo) >>f1 52 #the result: 53 # <class '__main__.Foo'> 54 # ('zxver',) {} 55 self.__init__(obj,*args, **kwargs) #Foo.__init__(f1,*args, **kwargs) 56 return obj 57 58 59 class Foo(metaclass=MyType): #Mytype(self,'Foo',(object,),{}),four attributes 60 def __init__(self,name): 61 self.name = name #obj,f1.name = name 62 63 # print(Foo) 64 f1 = Foo('zxver') 65 # print(f1.__dict__) 66 print(f1) 67 print(f1.__dict__)
6:Make classmethod:
1 class ClassMethod: 2 def __init__(self,func): 3 self.func=func 4 5 def __get__(self, instance, owner): #类来调用,instance为None,owner为类本身,实例来调用,instance为实例,owner为类本身, 6 def feedback(*args,**kwargs): 7 print('在这里可以加功能啊...') 8 return self.func(owner,*args,**kwargs) 9 return feedback 10 11 class People: 12 name='linhaifeng' 13 @ClassMethod # say_hi=ClassMethod(say_hi) 14 def say_hi(cls,msg): 15 print('你好啊,帅哥 %s %s' %(cls.name,msg)) 16 17 People.say_hi('你是那偷心的贼') 18 19 p1=People() 20 p1.say_hi('你是那偷心的贼')