gpt4 book ai didi

Python条件对象实例化

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:17 25 4
gpt4 key购买 nike

我正在参加在线 MOOC 类(class),但我很难弄清楚这一点,甚至无法准确地表达我正在试图弄清楚的内容。问题是要求仅当某个字符串作为参数传入时才创建对象。您可以在此处查看问题的描述:https://docs.google.com/forms/d/1gt4McfP2ZZkI99JFaHIFcP26lddyTREq4pvDnl4tl0w/viewform?c=0&w=1具体部分在第三段。使用“if”作为 init 的条件是否合法?谢谢。

最佳答案

用途:

def __new__( cls, *args):

而不是

def __init__( self, *args):

参见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

关于Python条件对象实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31714824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com