zoukankan      html  css  js  c++  java
  • Python __new__实现父类调用父类或子类的方法

    需求:当实例化子类时,需要让父类调用实现子类方法或子类没有实现调用的方法调父类的方法的需求。
    注意:此代码来源Tornado源码

    一、实例化子类调用父类的方法的示例

    class Base(object):
    
        def __new__(cls, *args, **kwargs):
            cls.config(cls)
            return super(Base, cls).__new__(object)
    
        @staticmethod
        def config(cls):
            print('Base.config')
    
    class Config(Base):
        def __new__(cls, *args, **kwargs):
            return super(Config, cls).__new__(cls, *args, **kwargs)
    
    if __name__ == '__main__':
        c = Config() # Base.config

    二、实例化子类父类调用子类的方法的示例

    class Base(object):
    
        def __new__(cls, *args, **kwargs):
            cls.config(cls)
            return super(Base, cls).__new__(object)
    
        @staticmethod
        def config(cls):
            print('Base.config')
    
    class Config(Base):
        def __new__(cls, *args, **kwargs):
            return super(Config, cls).__new__(cls, *args, **kwargs)
    
        @staticmethod
        def config(cls):
            print('Config.config')
    
    if __name__ == '__main__':
        c = Config() # Config.config

    三、小结

    从Tornado源码中发现如下代码:总结出来的规律
    下面代码是伪代码,实现代码请查看Tornado源码
    from typing import Type, Any
    
    class Configurable(object):
        def __new__(cls, *args: Any, **kwargs: Any) -> Any:
            pass
        @classmethod
        def configurable_base(cls):
            raise NotImplementedError()
    
        @classmethod
        def configurable_default(cls):
            raise NotImplementedError()
    
    class AsyncHTTPClient(Configurable):
        
        def __new__(cls, force_instance: bool = False, **kwargs: Any) -> "AsyncHTTPClient":
            ...
            instance = super(AsyncHTTPClient, cls).__new__(cls, **kwargs)  # 调用你类的__new__方法
            ...
    
        @classmethod
        def configurable_base(cls) -> Type[Configurable]:
            return AsyncHTTPClient
    
        @classmethod
        def configurable_default(cls) -> Type[Configurable]:
            from tornado.simple_httpclient import SimpleAsyncHTTPClient
            return SimpleAsyncHTTPClient
  • 相关阅读:
    Linux定时任务编写
    Linux编辑器的选择使用
    nginx配置中文域名解析
    Linux中统计某个文件夹的大小
    nginx配置文件的说明
    获取自身ip
    Python之时间模块、random模块、json与pickle模块
    python之os模块详解
    日志模块logging介绍
    Python面向过程、模块的使用
  • 原文地址:https://www.cnblogs.com/ygbh/p/14035994.html
Copyright © 2011-2022 走看看