Drying Duplicate Classes

I have different classes Class1 , Class2 , Class3 , etc., all of which contain this exact fragment inside:

 def showName(self): openWindow() print self.name 

For instance:

 class Class1: # SOME CODE def showName(self): openWindow() print self.name # SOME MORE CODE 

What is the best way to have showName defined once in a separate file and import it back into Class1 , Class2 , Class3 , etc.?

+4
source share
2 answers

Derive from this mixin :

 class NameShowMixin(object): def showName(self): openWindow() print self.name 

Or make it a separate function if you intend name be a public member.

+4
source

The idea of ​​the mixin class, introduced by larsmans, is a canonical way to do this. An alternative way is to put the function in another module and import it into each class definition:

 class Class1(object): from mixins import showName # other definitions here 

Your challenge is whether this is clearer than multiple inheritance.

+2
source

Source: https://habr.com/ru/post/1391653/


All Articles