我正在参加在线 MOOC 课程,但我很难弄清楚这一点,甚至无法准确地表达我正在试图弄清楚的内容。问题是要求仅当某个字符串作为参数传入时才创建对象。您可以在这里看到问题的描述:https://docs.google.com/forms/d/1gt4McfP2ZZkI99JFaHIFcP26lddyTREq4pvDnl4tl0w/viewform ?c=0&w=1 具体部分在第三段中。使用“if”作为init的条件是否合法?谢谢。
使用:
def __new__( cls, *args):
Run Code Online (Sandbox Code Playgroud)
代替
def __init__( self, *args):
Run Code Online (Sandbox Code Playgroud)
请参阅中止实例创建,尤其是new和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!"
Run Code Online (Sandbox Code Playgroud)
__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
Run Code Online (Sandbox Code Playgroud)