小编Adi*_*iva的帖子

Python 中基于参数的条件继承

作为 OOP 的新手,我想知道是否有任何方法可以根据子类在 Python 中的调用方式继承多个类之一。我尝试这样做的原因是因为我有多个同名的方法,但在三个具有不同功能的父类中。在创建对象时,必须根据某些条件继承相应的类。

例如,我试图根据实例化时是否传递任何参数来使C类继承A或B,但没有成功。谁能建议更好的方法来做到这一点?

class A:
    def __init__(self,a):
        self.num = a

    def print_output(self):
        print('Class A is the parent class, the number is 7',self.num)

class B:
    def __init__(self):
        self.digits=[]

    def print_output(self):
        print('Class B is the parent class, no number given')

class C(A if kwargs else B):
    def __init__(self,**kwargs):
        if kwargs:
            super().__init__(kwargs['a'])
        else:
            super().__init__()

temp1 = C(a=7)
temp2 = C()

temp1.print_output()
temp2.print_output()
Run Code Online (Sandbox Code Playgroud)

所需的输出将是“A 类是父类,编号是 7”,后跟“B 类是父类,没有给出编号”。

谢谢!

python oop inheritance

6
推荐指数
1
解决办法
4927
查看次数

标签 统计

inheritance ×1

oop ×1

python ×1