如何使用从 python 中的接口继承的第二个 parent class 方法?

How to use the second parent class methods which is inheriting from an interface in python?

我正在尝试实现一个接口,这个接口被两个具体的 class 接受,比如 class Firstclass Second,我有另一个 class 接受这些两个 class 作为一个 parent class COclass CO 根据 return 两个继承的 class 中的哪一个的标志做出决定,以便使用它们的实现。

from abc import ABC, abstractmethod

class common(ABC):
    @abstractmethod
    def firstfunction(self):
        pass 

    @abstractmethod
    def secondfunction(self):
        pass

class First(common):
    def __init__(self)-> boto3:
        self.ert = "danish"
        # self.username = kwargs["username"]
        # self.password = kwargs["password"]

        print("Inside First function")

    def firstfunction(self):
        print("My implementation of the first function in FIRST CLASS")

    def secondfunction(self):
        print("My implementation of the second function in FIRST CLASS")   

class Second(common):
    def __init__(self):
        self.rty = "pop"
        # self.session_id = kwargs["session_id"]

        print("Inside Second function")

    def firstfunction(self):
        print("My implementation of the first function in SECOND CLASS")

    def secondfunction(self):
        print("My implementation of the second function in SECOND CLASS")

class CO(First, Second):
    def __init__(self):
        self.inst = self.jo()

    def jo(self):
        a = True 

        if a:
            main_object = First()
            return main_object
        else:
            main_object = Second()

我正在实例化并调用方法

mymainclass = co()
objt = mymainclass

objt.firstfunction()
objt.secondfunction()

所以我的条件是,如果 CO class 中的 flag a = True 那么应该使用方法的具体 class First 实现,我们应该得到这样的输出:

Inside the First function

My implementation of the first function in FIRST CLASS

My implementation of the second function in FIRST CLASS

如果 CO class 中的 flag a = False 那么应该使用具体的 class Second 并且我们应该得到这样的输出:

Inside the Second function

My implementation of the first function in FIRST CLASS

My implementation of the second function in FIRST CLASS

从给定的代码中,我得到了标志 a = False 的以下输出:

Inside the Second function

My implementation of the first function in FIRST CLASS

My implementation of the second function in FIRST CLASS

有人可以使这段代码工作吗?我究竟做错了什么?我知道我可以创建一个函数,将这两个 classes 作为变量,然后根据条件 return 我想要的。但我想使用 classes 来实现相同的

好吧,我认为在这种情况下,CO class 必须来自common class 并实现第一个和第二个功能。在实现中,它会使用 First 或 Second classes 函数取决于 jo 函数的结果。这是正确的 Co class 代码:

class CO(common):

    def __init__(self):
        self.inst = self.jo()

    def jo(self):
        a = False

        if a:
            return First()

        return Second()

    def firstfunction(self):
        self.inst.firstfunction()

    def secondfunction(self):
        self.inst.secondfunction()


a = CO()
a.firstfunction()
a.secondfunction()

您可以直接使用class名称调用您想要的方法。

除非你有一些紧迫的理由去做你没有包括在你的问题中,否则我会避免这种情况而支持 returns FirstSecond 实例取决于输入。

class common(ABC):
    @abstractmethod
    def firstfunction(self):
        pass 

    @abstractmethod
    def secondfunction(self):
        pass

class First(common):
    def __init__(self):
        self.ert = "danish"
        super().__init__(self)
    def firstfunction(self):
        print("My implementation of the first function in FIRST CLASS")

    def secondfunction(self):
        print("My implementation of the second function in FIRST CLASS")   

class Second(common):
    def __init__(self):
        self.rty = "pop"
        super().__init__(self)
    def firstfunction(self):
        print("My implementation of the first function in SECOND CLASS")

    def secondfunction(self):
        print("My implementation of the second function in SECOND CLASS")

class CO(First, Second):
    def __init__(self):
        super().__init__(self)
    def use_first(self):
        return True or False  # whatever logic you have for determining this
    def firstfunction(self):
        if self.use_first():
            return First.firstfunction(self)
        else:
            return First.firstfunction(self)

我不会从 FirstSecond 继承 class CO,因为你希望最终得到的对象是 class First class Second 的实例。最直接的方法是定义方法 __new__,这将使您更好地控制实例创建。

保持所有代码不变(修复明显的错误后,例如 boto3 未定义)并更改 class CO 如下:


class CO:
    def __new__(cls):
        a = True

        if a:
            main_object = First()
        else:
            main_object = Second()
        return main_object

o = CO()
print(type(o))

打印:

Inside First function
<class '__main__.First'>

如果您想更好地参数化实例创建(并简化 __new__ 中的代码),则将变量 a 作为 CO 的参数:

class CO:
    def __new__(cls, a):
        return First() if a else Second()

o = CO(False)
print(type(o))

打印:

Inside Second function
<class '__main__.Second'>

您可以选择让 class COcommon 作为其基础 class 以记录实例化此 class 的实例会实现common 界面。但这样做不会导致强制执行 __new__:

返回的实际类型
class CO(common):
    def __new__(cls, a) -> common:
        # The Python interpreter is not type-checking what is returned:
        #return First() if a else Second()
        return []

o = CO(False)
print(type(o))

打印:

<class 'list'>

你也可以用工厂函数代替class CO:

def common_factory(a):
    return First() if a else Second()

o = common_factory(False)

备注

如果你想确保从基础 class common 继承的 class 必须覆盖 firstfunctionsecondfunction 以更接近地模拟在其他 object-oriented 语言中实现的纯接口,那么您应该在 common 中定义这些函数,以便它们引发 NotImplementedError 异常:

class common(ABC):
    @abstractmethod
    def firstfunction(self):
        raise NotImplementedError

    @abstractmethod
    def secondfunction(self):
        raise NotImplementedError

不幸的是,强制执行是在 运行 时完成的,伴随着惊喜,而不是像在其他 object-oriented 语言中那样在编译时完成。