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