当python对象通过obj=object.new(SomeClass)生成时会发生什么

2024-06-06 18:11:26 发布

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

我正在尝试用python创建一个单例类。 我在Stackoverflow的一个例子中发现了

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        print "New called"
        if cls._instance:
            return cls._instance
        cls._instance = super(Singleton, cls).__new__(
                cls, *args, **kwargs)
        return cls._instance


if __name__ == '__main__':
    s1=Singleton()
    s2=Singleton()
    if id(s1)==id(s2):
        print "Same"
    else:
        print "Different"
    print id(s1)
    print id(s2)

到目前为止,它给了我一个很好的单子,但当我用它做一个对象

s3 = object.__new__(Singleton)

它给了我一个全新的对象。 每次我通过对象创建一个实例时,它都会给我一个新实例。你知道吗

它没有调用Singleton类的new方法来创建新对象。 我的问题是如何生成一个既能处理s1=singleton()又能处理s3=object的singleton


Tags: 对象instanceidnewreturnifobjects3
2条回答

object.__new__中,您明确地说,您希望使用object的新方法,而不是Singleton的新方法。那么为什么要使用这个方法来创建Singleton?你知道吗

object.__new__()YourClass.__new__()不同

当您调用YourObject时,实例被添加到YourObject,并设置为None(记住它是静态的)。 但是,当您调用object.__new()时,object中不存在任何名为_instance的变量,因此当您调用YourObject时,它被赋值为None。简而言之:当您使用类object__new__时,您的实例逻辑没有被检查。你知道吗

class Singleton(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        print "New called"
        if cls._instance:
            return cls._instance
        cls._instance = super(Singleton, cls).__new__(
                cls, *args, **kwargs)
        return cls._instance


if __name__ == '__main__':
    s1=object.__new__(Singleton)
    print Singleton._instance
    s2=Singleton()
    if id(s1)==id(s2):
        print "Same"
    else:
        print "Different"
    print id(s1)
    print id(s2)


I have no name!@sla-334:~/stack_o$ python trick.py 
None
New called
<__main__.Singleton object at 0xb72e3e0c>
Different
3073261036
3073261068
I have no name!@sla-334:~/stack_o$

相关问题 更多 >