【发布时间】:2017-03-15 21:22:30
【问题描述】:
我目前正在使用 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(name, value, attrs)
RuntimeError: super(): __class__ cell not found
是工厂使用不当还是其他原因?
5 分钟后编辑 好的,我只需要通过调用 super(type(self), self) 来填充超级单元格。不太清楚它是如何工作的,但是,嘿,它奏效了!
谢谢大家!
【问题讨论】:
-
可能是元类的用例
-
自定义类的创建,通常使用metaclasses。具体应用视实际需求而定。
标签: python python-3.x oop inheritance