使用现代Python 3时,mixin或工厂的外观如何? [英] How could a mixin or factory look like using modern Python 3?

查看:78
本文介绍了使用现代Python 3时,mixin或工厂的外观如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我们有一些文件:

scheme.py

scheme.One.py

scheme.Two.py

sceme。*。py

...

Imagine, we have a some files:
scheme.py
scheme.One.py
scheme.Two.py
sceme.*.py
...

在文件'scheme.py'中,我们具有所有类属性的通用类代码

In file 'scheme.py' we have the common class code with all class attributes we need.

class Scheme:
    _VAR = "Variable"
    def function_common(self):
        pass
    def function_first(self):
        return "Main_Scheme"
    def function_second(self):
        return "Common_Scheme"

在其他文件中,我们只有ONLY PARTICULAR属性,我们希望在普通类中替换该属性。

In other files we have the ONLY PARTICULAR attributes, which we want to replace in common class.

文件'scheme.One.py':

File 'scheme.One.py':

class Scheme:
    _VAR = "Scheme1"
    def function_first(self):
        return "Scheme_One"

文件'scheme.Two.py':

File 'scheme.Two.py':

class Scheme:
    _VAR = "Scheme2"
    def function_second(self):
        return "Second_Scheme"

我们需要通过一些参数(不是问题)来确定关闭方案,并获得合适的类Scheme。

如果我们需要像这样的类工厂,这种情况的最佳实践是什么?文件'scheme.py'?

我不是Python专业人士。

请彻底回答...

任何Python版本(> = 3.74 ),感谢您提供现代解决方案...

非常感谢!!!

We need to determine the close scheme by some parameters (not in question) and get the appropriate class Scheme.
What is the best practice for this case, if we need to get like a "Factory of classes" in file 'scheme.py'?
I'm not PRO in Python.
Please, thorough answer...
Any Python version (>=3.74), appreciate for modern solutions...
Thanks very much!!!

推荐答案

我有@quamrana解决方案的修改版本。它使用工厂类而不是工厂函数,因此如果要在以下位置使用 __ init __(),则可能会更加灵活:

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:

class Main_Scheme:
    _VAR = "Variable"
    def function_common(self):
        pass
    def function_first(self):
        return "Main_Scheme"
    def function_second(self):
        return "Common_Scheme"

class Scheme1(Main_Scheme):
    _VAR = "Scheme1"
    def function_first(self):
        return "Scheme_One"

class Scheme2(Main_Scheme):
    _VAR = "Scheme2"
    def function_second(self):
        return "Second_Scheme"

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


class Scheme:

    def __new__(cls, mixin):

         return _mixins[mixin]()


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

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

(灵感来自 https://stackoverflow.com/a/5953974/7919597

这篇关于使用现代Python 3时,mixin或工厂的外观如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆