这个问题是关于Python继承的,但用 Django 示例进行了解释,但这应该不会受到伤害。
我有这个 Django 模型,Page还有RichText模型:
class Gallery(Page, RichText):
def save(self, *args, **kwargs):
# lot of code to unzip, check and create image instances.
return "something"
我只对save在另一个类中使用该方法感兴趣。
一个解决方案可能是:
class MyGallery(models.Model):
def save(self, *args, **kwargs):
# here goes the code duplicated from Gallery, the same.
return "something"
我想避免代码重复,而且我对从Pageand继承成员不感兴趣RichText(所以我不想这样做class MyGallery(Gallery):。如果它是合法的,我会写这样的东西:
class MyGallery(models.Model):
# custom fields specific for MyGallery
# name = models.CharField(max_length=50)
# etc
def save(self, *args, **kwargs):
return Gallery.save(self, *args, **kwargs)
但它不起作用,因为save()in需要一个, notGallery的实例。GalleryMyGallery
有什么方法可以“分离”该save()方法并按照那里定义的方式Gallery使用它?MyGallery
编辑:
我忘了说这Gallery是给定的,不能改变。