Skip to content Skip to sidebar Skip to footer

How Could A Mixin Or Factory Look Like Using Modern Python 3?

Imagine, we have a some files: scheme.py scheme.One.py scheme.Two.py sceme.*.py ... In file 'scheme.py' we have the common class code with all class attributes we need. class Sch

Solution 1:

You can have a factory which encapsulates all your specified files.

Imagine you have another separate module with a function: makeS3()

classMain_Scheme:
    _VAR = "Variable"deffunction_common(self):
        pass
    deffunction_first(self):
        return"Main_Scheme"deffunction_second(self):
        return"Common_Scheme"classScheme1:
    _VAR = "Scheme1"deffunction_first(self):
        return"Scheme_One"classScheme2:
    _VAR = "Scheme2"deffunction_second(self):
        return"Second_Scheme"

_mixins = {"Scheme1":Scheme1, "Scheme2":Scheme2}

defmakeS3(mixin):
    classScheme3(_mixins[mixin], Main_Scheme):
        pass
    return Scheme3()

Your clients can specify which mixin to take:

s3 = makeS3('Scheme1')
print(s3._VAR)

s3 = makeS3('Scheme2')
print(s3._VAR)

Solution 2:

I have a modified version of @quamrana's solution. It uses a factory class instead of a factory function, so you might be more flexible if you want to use __init__() somewhere:

classMain_Scheme:
    _VAR = "Variable"deffunction_common(self):
        pass
    deffunction_first(self):
        return"Main_Scheme"deffunction_second(self):
        return"Common_Scheme"classScheme1(Main_Scheme):
    _VAR = "Scheme1"deffunction_first(self):
        return"Scheme_One"classScheme2(Main_Scheme):
    _VAR = "Scheme2"deffunction_second(self):
        return"Second_Scheme"

_mixins = {"Scheme1":Scheme1, "Scheme2":Scheme2}


classScheme:def__new__(cls, mixin):

         return _mixins[mixin]()


s3 = Scheme('Scheme1')
print(s3._VAR)

s3 = Scheme('Scheme2')
print(s3._VAR)

(Inspired by https://stackoverflow.com/a/5953974/7919597)

Post a Comment for "How Could A Mixin Or Factory Look Like Using Modern Python 3?"