Skip to main content
 首页 » 编程设计

python之一个Python类可以不继承多个类,而是有一个 "choice"的继承吗

2025年05月04日24Leo_wl

我目前正在使用 3Rd 方应用程序。这个第 3 方应用程序定义了这些类:

 class VeryBaseClass(object): 
      def __init__(): 
          pass 
 
 class BaseClass(VeryBaseClass): 
     def specific_method(): 
          pass 

然后,论文的战利品:

 class Componenent[1,2,3,4....129883](BaseClass): 
     def other_specific_method(): 
         pass 

我无法修改这些类中的任何一个。所以,为了让我在这里覆盖/补充方法,我只需要创建一个继承自 Component 的类,我可以在其中毫不费力地更改方法。

问题是,制作 MyComponent1、MyComponent2、MyComponent3 等...所有这些都是为了在类的内容中复制粘贴完全相同的代码,而只是更改继承是非常烦人的,而且根本不是 DRY!

那么,有没有办法创建,例如,这个类:

class MyComponentGeneric(Component1, Component2, Component3....): 
      pass 

MyComponentGeneric 不会从列出的每个类继承,但可以从一个或另一个继承,具体取决于我对实例的声明?

谢谢!

使用更具体的代码进行编辑:

实际上,我已经尝试了属于每个答案的东西,但我总是面临同样的错误:

我按照 Chepney 的建议建立了一个工厂:

# This method is the one I use as a replacement 
def newrender(self, name, value, attrs=None): 
    result = super().render(name, value, attrs) 
    if self.image is None: 
        return result 
    else: 
        return '<img class="form-image" height="100" width="100" src="{}"/>'.format(self.image.url) + result 
 
 
def MyWidgetFactory(widget, picture): 
     newclass = type("WithImage" + widget.__name__, (widget,), dict(render=newrender)) 
     newclass.image = image 
     return newclass() 

但是一旦我的 newrender 方法启动,我就会收到这个错误:

result = super().render(名称, 值, 属性) RuntimeError: super(): 找不到 __class__ 单元格

是因为工厂使用不当还是其他原因?

5 分钟后编辑 好的,我只需要通过调用 super(type(self), self) 来填充 super 单元格。不太清楚它是如何工作的,但是,嘿,它起作用了!

谢谢大家!

请您参考如下方法:

这是一个字典的用例(或者可能是一个列表,如果字典键只是一系列连续的整数):

base_classes = { 
    1: Component1, 
    2: Component2, 
    # ... 
} 
 
def ComponentFactory(comp_type): 
    return base_classes(comp_type)() 

在这里,ComponentFactory 为您创建实例,而不是创建一个新类,该类实际上只是包装现有类而不实际添加到它。


如果您真的需要一个新类型,您也可以在工厂中创建它:

def ComponentFactory(comp_type): 
    new_type = type('SomeTypeName', (base_classes[comp_type],), {}) 
    return new_type() 

但是,您可能应该注意只为每个实际类创建一个这样的包装器,这样您就不会得到一堆相同的单例类。