zoukankan      html  css  js  c++  java
  • Python学习————反射

    一:什么是反射

    指的是在程序运行过程中可以“动态(不见棺材不落泪)”获取对象的信息(数据属性、函数属性)

    # 静态:在定义阶段就确定类型
    # 动态:在调用阶段才去确定类型
    

    二:为何要用反射

    def func(obj):
        if 'x' not in obj.__dict__:
            return
        obj.x
    
    
    func(10)        # AttributeError: 'int' object has no attribute '__dict__'
    

    三:实现反射机制的步骤

    1.先通过多dir:查看某一个对象下 可以.出哪些属性来

    print(dir(obj))     #  ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say']
    

    2.可以通过字符串反射到真正的属性上,得到属性值

    print(obj.__dict__['name'])     # xxq
    print(obj.__dict__[dir(obj)[-2]])     # xxq
    

    四:四个内置函数的使用:通过字符串来操作属性值

    1.hasattr()
    print(hasattr(obj, 'name'))     # True
    print(hasattr(obj, 'x'))        # False
    
    2.getattr()
    print(getattr(obj, 'name'))     # xxq
    print(getattr(obj, 'x'))        # AttributeError: 'People' object has no attribute 'x'
    
    3.setattr()
    print(getattr(obj, 'name', 'EGON'))     # 修改名字为EGON
    print(obj.name)                 # EGON
    
    4.delattr()
    delattr(obj, 'name')
    print(obj.__dict__)     # {'age': 18}
    

    获取对象和类

    res1 = getattr(obj, 'say')      # obj.say
    res2 = getattr(People, 'say')      # People.say
    print(res1)     # <bound method People.say of <__main__.People object at 0x0167B0B8>>
    print(res2)     # <function People.say at 0x016783D0>
    

    查看是否有这个方法

    obj = 10
    if hasattr(obj, 'x'):
        print(getattr(obj, 'x'))
    else:
        print('找不到')      # 找不到
    
    print(getattr(obj, 'x', None))   # None
    
    print(getattr(People, 'say', None))   # <function People.say at 0x01AC83D0>
    
    if hasattr(obj, 'x'):
        setattr(obj, 'x', 1111111)      # 10.x = 1111111
    else:
        print('找不到')  # 找不到
    

    基于反射可以十分灵活地操作对象的属性,比如将用户交互的结果反射到具体的功能执行

    class Ftp:
        def upload(self):
            print('正在上传')
    
        def download(self):
            print('正在下载')
    
        def interactive(self):
            method = input('>>>: ').strip()  # method = 'upload'
    
            if hasattr(self, method):
                getattr(self, method)()
    
            else:
                print('该指令不存在!')
    
    
    obj = Ftp()
    obj.interactive()
    

    二、内置方法

    1 什么是内置方法

    定义在类内部,以__开头和结尾的方法

    特点:在达成某种情况会自动触发执行

    2 为什么要用内置方法

    为了定制我们的类或者对象

    3 如何使用内置方法

    str

    在打印对象的时候会自动触发,然后把返回值(必须字符串)作为本次打印的输出结果

    这种方法我们在学习数据类型的时候就有接触过

    #x是int这个类实例化的结果
    x = 10 # x = int (10)
    # 打印x对象,本该获得x的内存地址
    print(x)
    # 直接获得了值是因为int类内部为我们设定了str,让我们打印对象直接得到值
    >>> 10
    

    转换成类

    class Foo:
        def __init__(self,name):
            self.name = name
    
        def __str__(self):
            return self.name
    obj = Foo('hz')
    print(obj)
    >>> hz
    

    del

    在清理对象时会触发,会先执行该方法

    class Foo:
        def __init__(self,name):
            self.name = name
    
    
        def __del__(self):
             # 发起系统调用,告诉操作系统回收相关的系统资源
            print('123213')
    
    obj = Foo('hz')
    print('----')
    
    >>> ----
    >>> 123213
    

    在执行完最后一行代码后才执行了del,是因为在程序结束的时候,我们会把对象清除,在清除之前就会执行del功能

    三、元类

    引子:python中一切皆对象

    1 什么是元类

    元类是用来实例化产生类的类

    关系:元类---实例化---->类(People)---实例化---->对象(obj)

    type是内置的元类

    在python中,class关键字定义的所有类,以及内置的类,都是由元类type实例化得到的

    2 class关键字创造类的步骤

    类有三大特征:类名,类的基类,执行类体代码得到名称空间

    通过下面拆解的方法我们实现了不用class去定义一个类

    # 1、类的名字
    class_name="People"
    # 2、类的基类
    class_bases=(object,)
    # 3、执行类体代码拿到类的名称空间
    class_dic={}
    class_body="""
    def __init__(self,name,age):
        self.name=name
        self.age=age
    
    def say(self):
        print('%s:%s' %(self.name,self.age))
    """
    exec(class_body,{},class_dic)
    # exec 执行第一个参数(必须字符串)中的python代码,把其中的全局作用域的名字转换成字典放在传给第二个参数,局部作用域的名字传给第三个参数
    
    People=type(class_name,class_bases,class_dic)
    obj = People('hz',18)
    obj.say()
    

    exec补充

    #exec:三个参数
    
    #参数一:包含一系列python代码的字符串
    
    #参数二:全局作用域(字典形式),如果不指定,默认为globals()
    
    #参数三:局部作用域(字典形式),如果不指定,默认为locals()
    
    #可以把exec命令的执行当成是一个函数的执行,会将执行期间产生的名字存放于局部名称空间中
    g={
        'x':1,
        'y':2
    }
    l={}
    
    exec('''
    global x,z
    x=100
    z=200
    
    m=300
    ''',g,l)
    
    print(g) #{'x': 100, 'y': 2,'z':200,......}
    print(l) #{'m': 300}
    

    3 自定义元类控制类的产生

    type是python内置的元类,所有的类都由type产生,但是当一个类继承于type时,他就成了一个自定义的元类

    class Mymeta(type): # 只有继承了type类的类才是元类
            # 空对象,"People",(),{...}
        def __init__(self, x, y, z):
            super().__init__(x,y,z)
            print('run22222222222....')
            # if not x.istitle():
            # raise NameError('类名的首字母必须大写啊!!!')
            # 当前所在的类,调用类时所传入的参数
        def __new__(cls, *args, **kwargs):
            # 造Mymeta的对象
            print('run1111111111.....')
            # print(cls,args,kwargs)
            # return super().__new__(cls,*args, **kwargs)
            return type.__new__(cls,*args, **kwargs)
    # 用自定义的元类 实例化得到类:People
    class People(metaclass=Mymeta):# metaclass指定元类
        def __init__(self,name,age):
            self.name=name
            self.age=age
    
        def say(self):
            print('%s:%s' %(self.name,self.name))
    调用我们自定义元类Mymeta会发生三件事,调用Mymeta就是调用type.__call__方法
    1、通过Mymeta中的__new__方法新建一个空对象
    2、调用Mymeta中的__init__方法完成对类的初始化操作
    3、返回初始化好的对象
    

    4 如何让对象可以被调用

    class Foo:
        def __init__(self,x,y):
            self.x=x
            self.y=y
    
        # obj,1,2,3,a=4,b=5,c=6
        def __call__(self,*args,**kwargs):
            print('===>',args,kwargs)
            return 123
    obj = Foo(1,2)
    print(obj)
    print(obj(1,2,3,a=4,b=5,c=6)) # 调用了Foo中的__call__
    >>> <__main__.Foo object at 0x000001FEAD9075C0>
    >>> ===> (1, 2, 3, 4, 8, 78, 89) {}
    >>> 123
    应用:如果想让一个对象可以加括号调用,需要在该对象的类中添加一个方法__call__
    总结:
    对象()->类内的__call__
    类()->自定义元类内的__call__
    自定义元类()->内置元类__call__
    
    5 自定义元类控制类的调用
    # 在实例化People对象的时候会通过它的元类Mymeta中的__call__方法去调用People类
    # obj=People()=》people.__call__=>干了3件事
    class Mymeta(type): # 只有继承了type类的类才是元类
        def __call__(self, *args, **kwargs):
            
            # 1、Mymeta.__call__函数内会先调用People内的__new__ 
            people_obj=self.__new__(self)
            
            # 2、Mymeta.__call__函数内会调用People内的__init__
            self.__init__(people_obj,*args, **kwargs)
    
            # print('people对象的属性:',people_obj.__dict__)
            # 附加:可以对新对象指定默认值
            people_obj.__dict__['xxxxx']=11111
            
            # 3、Mymeta.__call__函数内会返回一个初始化好的对象
            return people_obj
    #以此类推,自定义元类的调用也是使用type的__call__去调用自定义元类来实现实例化
    # 类的产生
    # People=Mymeta()=》type.__call__=>干了3件事
    # 1、type.__call__函数内会先调用Mymeta内的__new__
    # 2、type.__call__函数内会调用Mymeta内的__init__
    # 3、type.__call__函数内会返回一个初始化好的对象
    

    属性查找

    原则:对象-》类-》父类

    切记:父类不是元类

    class Mymeta(type):
        n=444
    
    class Bar(object):
        # n=333
        pass
    
    class Foo(Bar):
        # n=222
        pass
    
    class Teacher(Foo,metaclass=Mymeta):
        # n=111
        def __init__(self,name,age):
            self.name=name
            self.age=age
    obj = Teacher('hz',18)
    
  • 相关阅读:
    VMware虚拟机Mac OS X无法调整扩展硬盘大小,更新xcode时出现磁盘空间不足
    打包时Xcode报:此证书的签发者无效Missing iOS Distribution signing identity
    iPhone私有API
    Xcode真机调试中"There was an internal API error"错误解决方法
    用C#通过反射实现动态调用WebService 告别Web引用
    MySQL、PostgreSQL、Ingres r3、MaxDB等开源数据库的详细比较
    jQuery Mobile 移动开发中的日期插件Mobiscroll使用说明
    SQL Server 2008|2012 阻止保存要求重新创建表的更改
    SQL Server如何启用xp_cmdshell组件
    Windows平台下利用APM来做负载均衡方案
  • 原文地址:https://www.cnblogs.com/x945669/p/12709547.html
Copyright © 2011-2022 走看看