19 描述符应用 与类的装饰器

上下文管理协议

class Open:
    def __init__(self,name):
        self.name = name
    def __enter__(self):
        print(‘执行enter‘)
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(‘执行exit‘)
with Open(‘a.txt‘) as f:
print(f)
print(‘______‘)
print(‘00000‘)

with open 执行了enter f为enter返回值
with open结束调用exit
如果遇到异常也调用exit exit返回值为True 结束with open继续运行
为False 程序崩掉

描述符本身应该定义为新式类 被代理的类也应该是新式类
必须把描述符定义成类属性 不能定义到构造函数中
严格遵守优先级:类属性 数据描述符 实例属性 非数据描述符 找不到
描述符应用:

class Typed:
    def __get__(self, instance, owner):
        print(‘get method‘)
        print(‘instance 参数 %s‘%instance)
        print(‘owner data %s‘%owner)
    def __set__(self, instance, value):
        print(‘set methhod‘)
        print(‘instance 参数 %s‘ % instance)
        print(‘value data %s‘ % value)
class People:
    name = Typed()
    def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self. salary = salary
p1 = People(‘AAA‘,19,30.8)
# p1.name = ‘BBB‘
# print(p1.__dict__)
# p1.name

上例++

class Typed:
    def __init__(self,key):
        self.key = key
    def __get__(self, instance, owner):
        print(‘get method‘)
        return instance.__dict__[self.key]
    def __set__(self, instance, value):
        print(‘set methhod‘)
        if type(value) == str:
            pass
        else:
            return
            instance.__dict__[self.key] = value
    def __delete__(self, instance):
        print(‘delete method‘)
        instance.__dict__.pop(self.key)
class People:
    name = Typed(‘name‘)
    def __init__(self,name,age,salary):
        self.name = name
        self.age = age
        self. salary = salary
p1 = People(‘AAA‘,19,30.8)
p1.name = ‘BBB‘
# print(p1.__dict__)
del p1.name

类的装饰器的基本原理

def deco(obj):
    print(‘+++++++‘,obj)
    obj.x = 1
    return obj
@deco
class Foo:
    pass
print(Foo.__dict__)

增强版

def Typed(**kwargs):
    def deco(obj):
        # print(‘---------->‘,kwargs)
        # print(‘类名++++‘,obj)
        # obj.x = 1
        for key,val in kwargs.items():
        setattr(obj,key,val)
        return obj
        print(‘=====>>‘,kwargs)
    return deco
@Typed(x=1,y = 2,z = 3)
class Foo:
    pass
print(Foo.__dict__)

进阶版++ 可增加属性 略
自定制属性

class Lazy:
    def __init__(self,func):
        print(‘======>‘)
        self.func = func
    def __get__(self, instance, owner):
        print(‘get‘)
        print(instance)
        print(owner)
val = self.func(instance)
return val

class Room:
    x = property(‘x‘)
    def __init__(self,name,width,length):
        self.name = name
        self.width = width
        self.length = length
# @property #area = property(area)
@Lazy
    def area(self):
        return self.width * self.length
r = Room(‘厕所‘,3,10)
print(r.area)
# print(Room.__dict__)

元类
元类是类的类 是类的模板
元类的实例为类 正如类的实例是对象
type是python中的一个内建元类 用来直接生成类

自定义元类

class MyType(type):
    def __init__(self,a,b,c):
        print(‘元类的构造函数执行‘)
    def __call__(self, *args, **kwargs):
        obj = object.__new__(self)
        self.__init__(obj,*args,**kwargs)
        return obj
class Foo(metaclass = MyType): #foo(none) = mytype(foo,‘foo,(),            {}---> __init__
    def __init__(self,name):
        self.name = name
f1 = Foo(‘alex‘)

原文地址:https://www.cnblogs.com/louzhiyuan/p/10461851.html

时间: 2024-07-31 20:48:42

19 描述符应用 与类的装饰器的相关文章

Python之旅的第28天(描述符、类的装饰器)

周末真好,时间充裕,都能按照要求自己练习,感觉就是好 一.描述符 上次针对描述符的内容,理解的非常不到位,所以我就特地找了新的内容好好看了看,总结一下就是下面这些 # 前天我大概知道类描述符的一些特性,以及什么是数据描述符和非数据描述符 # 今天白天没事琢磨了一下,顺便又看了看各种案例,貌似理解更深入了一些 # 数据描述符:就是这个类属性是由一个实现了__get__(),__set__(),__delete__()中方法的新式类搞定了 # 非数据描述符则是,没有__set__方法的 # 当时没有

Python进阶-----类的装饰器及应用

回顾什么是装饰器: 装饰器定义:本质就是函数(高阶函数),功能是为其他函数(对象)添加新功能 一.类的装饰器基本实现原理如下: 1 def deco(cls): 2 print('类的装饰器=========>') 3 print('='*20) 4 return cls 5 6 @deco #====> Foo = deco(Foo) 7 class Foo: 8 pass 二.上述的简单装饰器是没有参数的,现在我们加上参数 1 def cls_decorator(**kwargs): #支

用类作为装饰器装饰函数!

在python中我们可以利用一个函数作为装饰器来装饰另一个函数,但是装饰器只能是函数吗 ?当然了我们还可以使用类来作为装饰器! class A(object): def __init__(self,func): print('定义初始化函数') print('func name is %s'%func.__name__) self.__func = func def __call__(self): print('call 方法作为装起中的功能') self.__func() print('增加的

python描述符、property、函数(类)装饰器实例解析

1 import sys 2 3 ''' 4 当使用实例对象访问属性时,都会调用__getattribute__内建函数 5 __getattribute__查找属性的优先级 6 1.类属性 7 2.数据描述符 8 3.实例属性 9 4.非数据描述符 10 5.__getattr__() 11 12 #实例.属性 13 c.x ==>type(x).__dict__['x'].__get__(x,type(x)) 14 #类.属性 15 C.x ==>X.__dict__['x'].__get

【python】-- 类的装饰器方法、特殊成员方法

装饰器方法 类的另外的特性,装饰器方法:静态方法(staticmethod).类方法(classmethod).属性方法(property) 一.静态方法 在方法名前加上@staticmethod装饰器,表示此方法为静态方法 class Dog(object): def __init__(self,name): self.name = name @staticmethod #在方法前加上staticmethod 装饰器定义静态方法 def eat(): print("dog is eating&

类的装饰器方法、特殊成员方法

https://www.cnblogs.com/Keep-Ambition/p/7296492.html 装饰器方法 类的另外的特性,装饰器方法:静态方法(staticmethod).类方法(classmethod).属性方法(property) 一.静态方法 在方法名前加上@staticmethod装饰器,表示此方法为静态方法 class Dog(object): def __init__(self,name): self.name = name @staticmethod #在方法前加上st

python__高级 : 类当作装饰器

类在创建对象时,会调用 __init__ 初始化一些东西 , 然后 如果类中定义了 __call__ 方法,可以直接用  对象()  这种方法调用,所以可以用类来装饰函数: class Test(object): def __init__(self, func): print('----装饰-----') print('func name is %s' % func.__name__) self.__func = func def __call__(self, *args, **kwargs):

python - 用类写装饰器

这里用到了__call__的class内置参数 #类装饰器: class zsq(): #本质是定义一个参数,让装饰的主题传递至__call__方法内部 def __init__(self,obj): self.obj = obj #利用__call__将类转变为可执行 #__call__内相当于函数装饰器最外层 def __call__(self, *args, **kwargs): print("start") #返回主机函数 re = self.obj(*args, **kwar

python 类的装饰器

我们知道,在不改变原有代码的基础上,我们可以使用装饰器为函数添加新的功能.同理,一切皆对象,我们也可以使用装饰器为类添加类属性.what? def deco(obj): obj.x = 1 obj.y = 2 return obj @deco # Foo = deco(Foo) class Foo: pass print(Foo.__dict__) 上述的代码为Foo属性字典添加了x和y属性,但如果想添加'name' = 'harden'呢,这需要更灵活的定义了.so def deco(**kw