Python条件对象实例化

2024-09-25 00:33:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在上一门在线MOOC课程,我很难搞清楚这一点,甚至不知道如何准确地表达出我想要弄明白的东西。问题是,只有当某个字符串作为参数传入时,才能创建对象。您可以在这里看到问题的描述:https://docs.google.com/forms/d/1gt4McfP2ZZkI99JFaHIFcP26lddyTREq4pvDnl4tl0w/viewform?c=0&w=1具体部分在第三段中。使用“if”作为init的条件是否合法?谢谢。在


Tags: 字符串httpscomdocs参数ifinitgoogle
1条回答
网友
1楼 · 发布于 2024-09-25 00:33:58

使用:

def __new__( cls, *args):

而不是

^{pr2}$

参见abort instance creation,尤其是new and init的公认答案

编辑:我添加了我自己的以下代码,作为它如何工作的一个简单示例-在实际场景中,您需要的不仅仅是这些:

class MyClass:
    def __new__(cls,**wargs):
        if "create" in wargs: # This is just an example, obviously
            if wargs["create"] >0: # you can use any test here
                # The point here is to "forget" to return the following if your
                # conditions aren't met:
                return super(MyClass,cls).__new__(cls)
        return None
    def __init__(self,**wargs): # Needs to match __new__ in parameter expectations
        print ("New instance!")
a=MyClass()         # a = None and nothing is printed
b=MyClass(create=0) # b = None and nothing is printed
c=MyClass(create=1) # b = <__main__.MyClass object> and prints "New instance!"

在实例创建之前,__new__被称为,与__init__不同的是,它返回一个值-该值是实例。有关更多信息,请参阅上面的第二个链接-这里有一些代码示例,可以借用其中一个:

def SingletonClass(cls):
    class Single(cls):
        __doc__ = cls.__doc__
        _initialized = False
        _instance = None

        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
            return cls._instance

        def __init__(self, *args, **kwargs):
            if self._initialized:
                return
            super(Single, self).__init__(*args, **kwargs)
            self.__class__._initialized = True  # Its crucial to set this variable on the class!
    return Single

相关问题 更多 >