lundi 18 avril 2016

Should mixins use parent attributes?

I'm working on a python project where I need to use about 20 different classes implementing a list of functionalities such as : "download", "parse", "update", etc.

Several functionalities can easily be factorized by using a superclass since the required code is the same for all of them.

But sometimes, particularly for the "parse" method, I have 10 classes that must implement the same algorithm and 10 others that need a specific algorithm.

Based on what I know about python, this behavior can be easily factorized with the use of mixins.

But here is the problem even if the "parse" algorithm is the same, I need to apply a tag to parsed entries, and this tag is specific for each class. I wonder if this is a proper way to use a class attribute that will be used only by the mixin to achieve this goal.

This chunk of code give an example of how attributes are used :

class MyMixin():
    def parse(self):
        print(self.tag)
        ...

class MyClass(MyMixin):
    tag = 'mytag'

I already saw it in some frameworks (http://ift.tt/1qB7UkM), but I'm interested to know what's the opinion of the community.

Aucun commentaire:

Enregistrer un commentaire