Как передать экземпляр класса другому классу без наследования?

У меня есть 3 класса: API, AccountCategory и BaseCategory. В классе API есть метод выполнения запроса к API. Мне нужно воспользоваться этим методом в классе AccountCategory, который наследуется от BaseCategory.

class API:
    def execute_request(self, method: str, data: dict) -> dict:
        response = post("", dumps(data))
        return loads(response.text)


class BaseCategory:
    ...


class AccountCategory(BaseCategory):
    def set_system_proxy(self):
        response = None  # Здесь нужно использовать метод execute_request()

Как грамотно передать экземпляр класса API классу BaseCategory без наследования?


Ответы (1 шт):

Автор решения: Roman-Stop RU aggression in UA

Например, так:

class API:
    def execute_request(self, method: str, data: dict) -> dict:
        response = post("", dumps(data))
        return loads(response.text)


class BaseCategory:
    def __init__(self, api):
        self.api = api


class AccountCategory(BaseCategory):
    def set_system_proxy(self) -> dict:
        return self.api.execute_request("SetSystemProxy", None)


api = API()

account_category = AccountCategory(api)
account_category.set_system_proxy()
→ Ссылка