English 中文(简体)
使用来自其他等级的遗产继承方法
原标题:Use a method from other classes w/o inheritance

这个问题涉及`em>Python 继承问题,但用Django的例子解释,这应该会很痛。

我有这个Django模型,有 < code> Page 和 < code> RichText 模型,还有:

class Gallery(Page, RichText):
    def save(self, *args, **kwargs):
        # lot of code to unzip, check and create image instances.
        return "something"

我只有兴趣在另一类中使用 < code> save 方法。

解决办法可以是:

class MyGallery(models.Model):
    def save(self, *args, **kwargs):
        # here goes the code duplicated from Gallery, the same.
        return "something"

我想避免代码重复,我也不想继承 Page 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)

但不会起作用,因为 Gallery () () gallery 期望有 gallery ,而不是 MyGallery

是否有办法从 Gallery 调出 save () <() 方法,在 MyGallery 中使用,并在该方法定义的 MyGallery 中使用?

<强度 > EDIT:

我忘了说,Gallery 已经给出,无法更改。

最佳回答

您可以访问“http://docs.python.org/dev/reference/datamodel.html#index-35' rel=“nofollow”codefunc/code> 方法 save 的属性 :

class Gallery(object):
    def save(self, *args, **kwargs):
        return self, args, kwargs

class MyGallery(object):
    def save(self, *args, **kwargs):
        return Gallery.save.__func__(self, *args, **kwargs)
    # 或
    # save = Gallery.save.__func__

mg = MyGallery()
print mg.save( arg , kwarg= kwarg )
# (<__main__.MyGallery object at 0x04DAD070>, ( arg ,), { kwarg :  kwarg })

但是如果可能的话,你最好能重构因素:

class SaveMixin(object):
    def save(self, *args, **kwargs):
        return self, args, kwargs

class Gallery(SaveMixin, object):
    pass

class MyGallery(SaveMixin, object):
    pass

def gallery_save(self, *args, **kwargs):
    return self, args, kwargs

class Gallery(object):
    save = gallery_save

class MyGallery(object):
    save = gallery_save
问题回答

我不知道为什么你反对继承,特别是方法方面的继承。我经常创建一个 MixIn 类,由我所有的Django Model 模型继承。它包含建立 URL 、 倾弃等各种有用的方法。 我的确使用 hasatr () 的方法来保证它们适用于某个特定类别,但这样做确实节省时间。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...