Python组合:通过__new__方法实现成员类访问宿主类的方法
import inspect class BaseMessage(object): def __init__(self, client=None): self.client = client class Message(BaseMessage): message_key = 'message_key' def _is_api_endpoint(obj): return isinstance(obj, BaseMessage) class BaseClient(object): def __new__(cls, *args, **kwargs): ''' 让 Client 中所有 BaseMessage 子类实例(如 Message)自动关联 Client 实例,无需手动传参 ''' self = super(BaseClient, cls).__new__(cls) # 反射遍历实例属性,筛选出所有 BaseMessage 子类实例 # inspect.getmembers(self, 筛选函数):获取 self 的所有属性/方法,仅保留符合筛选条件的 api_endpoints = inspect.getmembers(self, _is_api_endpoint) print('api_endpoints:>>>>> ', api_endpoints) # [('message', <__main__.Message object at 0x1048c2010>)] # 遍历筛选结果,重新实例化并绑定 Client 实例 for name, api in api_endpoints: # 获取消息类的类型(如 Message) api_cls = type(api) # 等价于 api_cls = Message # 重新实例化:将 Client 自身(self)传入 Message 的 __init__ api = api_cls(self) # 把重新实例化后的 Message 绑定回 Client 实例的属性 setattr(self, name, api) return self API_BASE_URL = 'https://www.baidu.com/' class Client(BaseClient): message = Message() client = Client() print(client.message.message_key) # message_key print(client.message.client.API_BASE_URL) # 'https://www.baidu.com/'
~~~
浙公网安备 33010602011771号