代码之家  ›  专栏  ›  技术社区  ›  hasdrubal

抽象基类函数指针python

  •  2
  • hasdrubal  · 技术社区  · 10 月前

    我想对我的一个api类进行抽象,以解决以下问题。假设我有一个基类,比如:

    class AbstractAPI(ABC):
        @abstractmethod
        def create(self):
            pass
    
        @abstractmethod
        def delete(self):
            pass
    

    还有一个具体的类:

    class API(AbstractAPI):
        def create(self):
            print("create")
    
        def delete(self):
            print("delete")
    

    当请求传入时,我无法访问我的API实例。既要多线程处理,又要避免一些循环导入。在这一点上,我确实知道稍后我想调用哪种方法。因此,我的计划是将AbstractAPI的一个函数指针放在一个队列中,等待我访问API实例。

    function_pointer=AbstractAPI.create
    # later on ...
    function_pointer(ConcreteAPIInstance)
    

    此时,将函数指针调用到API实例上,ba-da-bim,ba-da boom。当然,在API实例上调用AbstractAPI的函数指针会调用空的AbstractAPI方法。什么都没发生。有办法让这个工作吗?

    2 回复  |  直到 10 月前
        1
  •  2
  •   khelwood Muhammed Elsayed.radwan    10 月前

    而不是直接引用抽象类方法 function_pointer=AbstractAPI.create ,您可以编写一个函数来调用指定的 create() 给定对象上的方法。

    function_pointer = lambda api : api.create()
    

    def function_pointer(api):
        return api.create()
    
        2
  •  2
  •   blhsing    10 月前

    一种方法是使用 operator.methodcaller 在调用时查找给定对象上的命名方法:

    from abc import ABC, abstractmethod
    from operator import methodcaller
    
    class AbstractAPI(ABC):
        @abstractmethod
        def create(self):
            pass
    
    class API(AbstractAPI):
        def create(self):
            print("create")
    
    function_pointer=methodcaller('create')
    function_pointer(API())
    

    这将输出:

    create