day28面向对象进阶

===============================自省===============================
    hasattr(obj,'属性')->>有属性是否存在
    getattr(obj,'属性')->>获取属性是否存在,不存在报错
    delattr(obj,'属性','默认值')->>获取obj.属性  不存在不会报错,返回那个默认的值
    setattr(obj,'属性','属性的值')obj.属性=属性的值
    delattr(obj,'属性')->>del obj.属性
        __getattr__:obj[属性]的方式去操作属性时候时触发的方法
        __setattr__:
        __delattr__:

        __getitem__:obj[属性] 时候触发
        __setitem__:obj[属性] =属性的值 触发
        __delitem__:obj[]

    描述符就是一个新式类,这个类至少实现以下杀个方法的一个
        __get__,
        __set__,
        __delete__,
        class Foo():
            def __get__():
                pass
            def __set__():
                pass
            def __delete__():
                pass
        class Bar():
            name='oulen'
        obj=Foo()
        obj.name='oulen'
    ==============__str__fan方法
    class Foo1(object):
        def __init__(self,name,age):
            self.name=name
            self.age=age
        def __str__(self)
            return "bar(%s %s)"%(self.name,self.age)
    b=Foo1('oulen',128) 
    print(b)       
================call方法
    class Foo():
        pass
        def __call__(self, *args, **kwargs):
            print('我执行啦obj()')

    f1=Foo()
    f1()#调用的就是__call__方法
============doc属性===========
    class Foo():
        '我是描述信息'
        pass
    class Bar():
        pass
    print(Foo.__dict__)
    print(Bar.__dict__)
=================文件描述符号================
    #f=open('a.txt')
    #文件操作
    # with open('a.txt','w') as f:
    #     f.writelines('你好')
    #     print(f.readline(1))

    class Foo():
        def __init__(self,name):
            self.name=name
        def __enter__(self):
            print('执行enter')
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            print('执行exit')
            print(exc_tb)
            print(exc_type)
            print(exc_val)
            return True
    with Foo('a.txt') as f:
        pass
        print(f)
        print(f.name)
        print('aiga')
        # print('->>>>>>>')
        # print('->>>>>>>')
        # print('->>>>>>>')
        # print('->>>>>>>')
    print('00000000000')

    #with obj as f:
        #'代码块'
    # with obj ->>触发obj.__enter__()方法,拿到返回值,
    #  as f--f=返回值

    #with obj as f= f=obj.__enter__()
    #执行代码快
    #一:没有异常的情况下,代码块运行完毕以后触发__exit__()运行,三个参数为None
    #二:有异常的情况下,从异常的位置触发__exit__()
        #a:如果__exit__的返回值是True代表吞掉异常
        #b:如果__exit__的返回值是不为True,代表吐出了异常
        #c:__exit__的运行完毕就代表整个with运行完毕
    #with open()#好处是能够执行自动清理

=====================================元类=============================
    # class Foo():
    #     pass
    #
    # f1=Foo()
    # print(type(f1))
    # print(type(Foo))
    # print(type(type))
    #
    # class Bar():
    #     pass

    #元类就是模板
    #元内是用来创建模板的,正如类是创建对象的模板
    #type 是python内置的元类

    class Foo():
        def __init__(self,name,age):
            self.name=name
            self.age=age
    def __init__(self,name,age):
        self.name=name
        self.age=age

    print(Foo)
    FFo=type('FFo',(object,),{'x':1,'__init__':__init__})
    print(FFo)
    f1=FFo('oulen',18)
    print(FFo.__dict__)

    #两种定义


=====================================利用描述符号自定义元类==================
    class Lazypropetry():
        def __init__(self,func):
            print('==============',func)
            self.func=func
        def __get__(self, instance, owner):
            print('get_')
            print(instance)
            print(owner)
            if instance is None:
                return self
            res=self.func(instance)
            setattr(instance,self.func.__name__,res)
            return res

    class Room():
        x=Lazypropetry('x')
        def __init__(self,name,width,length):
            self.name=name
            self.width=width
            self.length=length

        @Lazypropetry #
        def area2(self):
            return self.width * self.length
        @property #
        def area1(self):
            return self.width * self.length
        @property
        def test(self):
            return '1111111'
    # r1=Room('厕所',1,1)
    # print(r1.area)
    # print(Room.__dict__)
    r1=Room('cesuo',1,1)
    print(r1.area)
    #类调用
    #实例调用



    #类属性
    #数据描述符
    #实例属性
    #非数据描述符号
    #找不到

    print(r1.area)

=============================描述符的应用==========================
    class Typed:
        def __init__(self,key,expected_type):
            self.key=key
            self.expected_type=expected_type
        def __get__(self, instance, owner):
            print('get方法')
            # print('instance参数【%s】' %instance)
            # print('owner参数【%s】' %owner)
            return instance.__dict__[self.key]
        def __set__(self, instance, value):
            print('set方法')
            # print('instance参数【%s】' % instance)
            # print('value参数【%s】' % value)
            # print('====>',self)
            if not isinstance(value,self.expected_type):
                # print('你传入的类型不是字符串,错误')
                # return
                raise TypeError('%s 传入的类型不是%s' %(self.key,self.expected_type))
            instance.__dict__[self.key]=value
        def __delete__(self, instance):
            print('delete方法')
            # print('instance参数【%s】' % instance)
            instance.__dict__.pop(self.key)
    class People:
        name=Typed('name',str) #t1.__set__()  self.__set__()
        age=Typed('age',int) #t1.__set__()  self.__set__()
        def __init__(self,name,age,salary):
            self.name=name
            self.age=age
            self.salary=salary

    # p1=People('alex','13',13.3)
    p1=People(213,13,13.3)

    # p1=People('alex',13,13.3)
    # print(p1.__dict__)
    # p1=People(213,13,13.3)
    # print(p1.__dict__)
    # print(p1.__dict__)
    # print(p1.name)

    # print(p1.__dict__)
    # p1.name='egon'
    # print(p1.__dict__)


    # print(p1.__dict__)
    # del p1.name
    # print(p1.__dict__)

    # print(p1)

    # print(p1.name)
    # p1.name='egon'
    # print(p1.name)
    # print(p1.__dict__)

===================================类的装饰器=======================
    # def deco(func):
    #     print("------------")
    #     return func
    #
    # @deco
    # def test():
    #     print('test函数运行')
    #
    # test()
    # def deco(obj):
    #     print('----------',obj)
    #     return obj
    #
    # @deco
    # class Foo():
    #     print('nihao')
    # print(Foo.__dict__)

    def test():
        print('函数')
    test.x=1
    test.y=2
    print(test.x)
===========================类的装饰器的应用====================
    class Typed:
        def __init__(self,key,expected_type):
            self.key=key
            self.expected_type=expected_type
        def __get__(self, instance, owner):
            print('get方法')
            # print('instance参数【%s】' %instance)
            # print('owner参数【%s】' %owner)
            return instance.__dict__[self.key]
        def __set__(self, instance, value):
            print('set方法')
            # print('instance参数【%s】' % instance)
            # print('value参数【%s】' % value)
            # print('====>',self)
            if not isinstance(value,self.expected_type):
                # print('你传入的类型不是字符串,错误')
                # return
                raise TypeError('%s 传入的类型不是%s' %(self.key,self.expected_type))
            instance.__dict__[self.key]=value
        def __delete__(self, instance):
            print('delete方法')
            # print('instance参数【%s】' % instance)
            instance.__dict__.pop(self.key)
    def deco(**kwargs):
        def wrapper(obj):
            for key,val in kwargs.items():
                print('---',key,val)
                Typed(key,val)
                setattr(obj,key,val)
                setattr(obj,key,Typed(key,val))
                
            return obj
    class People:
        name=Typed('name',str) #t1.__set__()  self.__set__()
        age=Typed('age',int) #t1.__set__()  self.__set__()
        def __init__(self,name,age,salary,gender,height):
            self.name=name
            self.age=age
            self.salary=salary

    # p1=People('alex','13',13.3)
    # p1=People(213,13,13.3)

    print(People.__dict__)
    # p1=People('alex',13,13.3)
    # print(p1.__dict__)
    # p1=People(213,13,13.3)
    # print(p1.__dict__)
    # print(p1.__dict__)
    # print(p1.name)

    # print(p1.__dict__)
    # p1.name='egon'
    # print(p1.__dict__)


    # print(p1.__dict__)
    # del p1.name
    # print(p1.__dict__)

    # print(p1)

    # print(p1.name)
    # p1.name='egon'
    # print(p1.name)
    # print(p1.__dict__)

=================类的装饰器的修订版==========================
    def Type(**kwargs):
        def deco(obj):
            for key ,val in kwargs.items():
                setattr(obj,key,val)
                return obj
        print('+++',kwargs)
        return deco
    @Type(x=1,y=2,z=3) #Foo=deco(Foo)   #1.Type(x=1,y=2,z=3) ->>deco, 2@deco=------Foo=deco(Foo)

    class Foo():
        print('ooo')
==================自定制元类======================
    class MyType(type):
        def __init__(self,a,b,c):
            print('自定制元类')
            print(a)
            print(b)
            print(c)
        def __call__(self, *args, **kwargs):
            print('============')
            print(self)
            print(args,kwargs)
            obj=object.__new__(self)
            self.__init__(obj,**args,**kwargs)
            return obj
    class Foo(metaclass=MyType):#MyType(Foo,'Foo',,(object))
        def __init__(self,name):
            self.name=name

    f1=Foo('alex')
    print(f1)
    print(f1.__dict__)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章