zoukankan      html  css  js  c++  java
  • python-反射、新式类与经典类搜索的优先级

    preface

    include:

    1. getattr
    2. setattr
    3. delattr
    4. hasattr
    class webserver(object):
        def __init__(self,num):
            self.num=num
            def stop(self):
            print("Stop the server !!")
            
        def start(self):
            print("Start the server !!")
            
        def restart(self):
            self.stop()
            self.start()
            print("Restart the server")
            
        def run_test():
            print("Reload the server")
    
    if __name__ =="__main__":
        server=webserver(1)
        server2=webserver(1)
    

    hasattr

    if hasattr(server,sys.argv[1]):
        func=getattr(server,sys.argv[1])  # getattr其实是在server这个实例中寻找和sys.argv[1]这个字符串相同的方法,并且返回一个内存地址
           func()
    

    setattr

    setattr 是这么玩: setattr(x, 'y', v) is equivalent to ``x.y = v'',意思是第一个输入的是实例的名字,第二个是属性的别名,第三个函数名(类里面已有的方法)

    setattr(server,'reload',run_test)
    server.reload()
    

    delattr

    delattr 是这么玩 delattr(x, 'y') is equivalent to ``del x.y'' ,x是类名,y是类的方法名

    delattr(webserver,'start')
    

    此时我们把类的start方法删除后,对象server就没有start方法了,执行下面句的时候就会报错了

    server.start()
    ```
    
    
    #### 新式类与经典类搜索的优先级
    在python2.7  2.6版本内是这样的:
    1. 经典类是深度优先
    2. 新式类是广度优先
    在python3.0 版本是:
    1. 不关新式类还是经典类,都是广度优先。
    
    
    #### 例子:
    
    ```
    #!/usr/bin/env python
    '''
    类的继承之深度优先还是广度优先
    '''
    
    class A:
        def f1(self):
            print("f1 from A")
        def f2(self):
            print("f2 from A")
            
    class B:
        def f1(self):
            print("f1 from B")
        def f2(self):
            print("f2 from B")
    
    class C:
        def f1(self):
            print("f1 from C")
        def f2(self):
            print("f2 from C")
            
    class D(B,C):
        pass
    
    d=D()
    ```
    
    此时D继承了类B,C,那么执行f1方法的时候,首先从同样等级的父类的子类里面,从左往右执行。也就是首先从B里面找f1,f2,
    如果B里面没有f1,f2,那么就找C里面的,C里面也没有的话就往C和B的父类往上找,直到找到为止,这就是广度优先
    在python2.7  2.6版本内是这样的:
    1. 经典类是深度优先
    2. 新式类是广度优先
    
    在python3.0 版本是:
    不关新式类还是经典类,都是广度优先。
  • 相关阅读:
    形象理解ERP(转)
    禁用windows server 2008 域密码复杂性要求策略
    How to adding find,filter,remove filter on display method Form
    Windows Server 2008 R2激活工具
    How to using bat command running VS development SSRS report
    Creating Your First Mac AppGetting Started
    Creating Your First Mac AppAdding a Track Object 添加一个 Track 对象
    Creating Your First Mac AppImplementing Action Methods 实现动作方法
    Creating Your First Mac AppReviewing the Code 审查代码
    Creating Your First Mac AppConfiguring the window 设置窗口
  • 原文地址:https://www.cnblogs.com/liaojiafa/p/6718172.html
Copyright © 2011-2022 走看看