【问题标题】:Best way to handle preset options in classes在类中处理预设选项的最佳方法
【发布时间】:2019-07-28 09:39:43
【问题描述】:

我想要一个可以使用 abc 选项初始化的类。

c 是一种特殊情况,我可以使用变量extend 修改初始化。

我目前正在寻找执行此操作的最佳方法。 此外,我希望我的 IDE(在本例中为 PyCharm)向我提出可以用于预设的参数的建议。

我想出了两个想法。

选项 1:

class MyClass:
    def __init__(self,preset,extend=None):
        if preset == "a":
            self.x = 1
        if preset == "b":
            self.x = 2
        if preset == "c":
            self.x = 3
            if extend != None:
                self.x = self.x + extend
    def __str__(self):
        return f"The value of x is {self.x}"

Y=MyClass(preset="c",extend= 3)
print(Y)
#out: The value of x is 6

选项 2:

class MyClass2:
    def __init__(self):
        self.x=None
    def preset_a(self):
        self.x=1
    def preset_b(self):
        self.x=2
    def preset_c_with_extend(self,extend):
        self.x =3+extend

    def __str__(self):
        return f"The value of x is {self.x}"

Y2=MyClass2()
Y2.preset_b()
print(Y2)
#out: The value of x is 2

选项 1 对我来说看起来更优雅,但在我的工作流程中,我不想去实现初始化某个预设以查找选项。

但这将是必要的,因为如果我将预设命名为a 或者不是A,我不记得对于更大的项目。 选项 1 也不清楚我是否可以添加选项 extend。 这里可能会发生,我使用预设 aextend=3,我想知道为什么不应用扩展。

所以实际的问题是:有没有一种优雅的方法可以在不查看类实现的情况下查看预设选项? (也许是某种类型提示?)

选项 2 有这个机会,通过我的 IDE 中的自动完成功能,我可以看到可以应用哪些预设。但是看起来不是很优雅。

我很好奇你的想法!

【问题讨论】:

    标签: python class arguments


    【解决方案1】:

    怎么样:

    class MyClass2:
        def __init__(self, x):
            self.x = x
        @staticmethod
        def preset_a():
            return MyClass2(1)
        @staticmethod
        def preset_b():
            return MyClass2(2)
        @staticmethod
        def preset_c_with_extend(extend):
            return MyClass2(3+extend)
    
        def __str__(self):
            return f"The value of x is {self.x}"
    
    Y2=MyClass2.preset_b()
    print(Y2)
    

    它确保x 在对象创建时设置,并且应该允许 IDE 自动完成。

    【讨论】:

    • 哇,太美了!我喜欢它的递归部分。 IDE 自动完成也是可能的 :)
    【解决方案2】:

    另一种选择是使用预设dict。但是,我不知道 PyCharm 将如何处理该解决方案的建议。

    class MyClass:
        PRESETS = {"a": 1, "b": 2, "c": 3}
    
        def __init__(self, preset, extend=None):
            self.x = self.PRESETS.get(preset)
    
            if preset == "c" and extend is not None:
                self.x += extend
    
        def __str__(self):
            return f"The value of x is {self.x}"
    

    请注意,dict.get() 方法被使用,这意味着如果您尝试使用不存在的预设,x 将是 None

    【讨论】:

    • 谢谢,这比我的选项 1 更好,但是 @Michael Butscher 的解决方案更符合我的要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2013-03-08
    • 1970-01-01
    相关资源
    最近更新 更多