一个Python类不能从多个类继承,但是可以选择继承吗?

2024-10-02 18:14:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

 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

我不能修改这些类中的任何一个。所以,要在这里重写/补充方法,我只需要创建一个从组件继承的类,在这里我可以毫不费力地更改方法。你知道吗

问题是,生成MyComponent1,然后生成MyComponent2,MyComponent3,等等。。。所有的复制粘贴在类的内容完全相同的代码,只是改变继承是非常烦人的,而不是干的!你知道吗

那么,有没有一种方法可以创建,例如,这个类:

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

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

谢谢!你知道吗

用更具体的代码编辑:

事实上,我试过每一个答案中都包含的东西,但最终我总是面临同样的错误:

我按照切普尼的建议建立了一个工厂:

# 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(name, value, attrs) RuntimeError: super(): __class__ cell not found

是因为工厂使用不当还是其他原因?你知道吗

5分钟后编辑 好的,我只需要用super(type(self),self)来填充超级单元格。不太清楚它是怎么工作的,但是,嘿,它工作了!你知道吗

谢谢大家!你知道吗


Tags: 方法nameimageselfreturnvaluedefpass
2条回答

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

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()

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

首先,你不会把你的类命名为MyComponent2112,你会有一个以类为值的字典。更容易相处。你知道吗

然后在循环中创建类:

import third_party_module

mycomponents = dict()

for componentname in dir(third_party_module):
    if not componentname.startswith('Component'): continue
    baseclass = getattr(third_party_module, componentname)
    if not issubclass(baseclass, third_party_module.VeryBaseClass): continue
    number = int(componentname[9:])

    class MyComponent(baseclass):
        # Your updates here
    mycomponents[number] = MyComponent

相关问题 更多 >