简体   繁体   English

python 中的切换器给出的 Object 问题

[英]problem with Object given by switcher in python

I seem to have a problem with a switch-fashioned code when I try to create an object where its class depends on an input.当我尝试创建 object 其中 class 取决于输入时,我似乎遇到了开关式代码的问题。

Let us say there are two classes, Class1 and Class2.假设有两个类,Class1 和 Class2。 Both of them, when I create an object, give me a message "Object of Class<1 or 2> created" Then there is this new class which have a method that take a string when I create the object.他们两个,当我创建一个 object 时,给我一条消息“创建了 Class<1 或 2> 的对象”然后有这个新的 class 有一个方法在我创建 ZA8CFDE6331BD59EB2AC96F8911C4B66 时采用字符串this string is "Class1" or "Class2".这个字符串是“Class1”或“Class2”。

Here the tricky part: based on this string I create an object Class1 or an object Class2 as follows:这里是棘手的部分:基于这个字符串,我创建了一个 object Class1 或一个 object Class2 如下:

def type_to_object(self, type):
        switcher = {
            "Class1": Class1(),
            "Class2": Class2(),
        }
        return switcher.get(type, "Invalid Class")

Now, this worked well in similar cases.现在,这在类似情况下效果很好。 The problem here is that it seems to create both the objects, even if I only got one in return when I call the method (obviously).这里的问题是它似乎同时创建了两个对象,即使我在调用该方法时只得到了一个(显然)。 I say this because refering to what I said above, I get both the messages "Object of Class1 created" and "Object of Class2 created"我这样说是因为参考我上面所说的,我同时收到消息“已创建 Class1 的对象”和“已创建 Class2 的对象”

Thank you in advance先感谢您

PS: what it seems super strange, is that it should not enter all the cases, only the one equal to type PS:看起来超级奇怪的是,它不应该输入所有的case,只有一个等于type

The problem is that you create instances of both your classes in the switcher dictionary.问题是您在切换器字典中创建了两个类的实例。

Try this instead:试试这个:

class Class1:
    def __init__(self):
        self.who_am_i = "Class1"


class Class2:
    def __init__(self):
        self.who_am_i = "Class2"


def type_to_object(class_type):
    switcher = {
        "Class1": Class1,  # No parentheses here, we don't want an instance. Just a type
        "Class2": Class2,  #
    }
    selected_class = switcher.get(class_type, None)
    if selected_class is None:
        raise RuntimeError("Invalid Class")
    return selected_class()  # Now, we use parentheses: we want to create an instance


c = type_to_object("Class1")
print(c.who_am_i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM