confused about __new__

Ian Kelly ian.g.kelly at gmail.com
Tue Dec 27 15:34:08 EST 2011


On Tue, Dec 27, 2011 at 1:31 PM, K Richard Pixley <rich at noir.com> wrote:
> On 12/27/11 10:28 , Ian Kelly wrote:
>>
>> On Tue, Dec 27, 2011 at 10:41 AM, K Richard Pixley<rich at noir.com>  wrote:
>>>
>>> The conceptual leap for me was in recognizing that a class is just an
>>> object.  The best way, (imo, so far), to create a singleton in python is
>>> to
>>> use the class itself as the singleton rather than ever instantiating it.
>>>  With a little work, you can even prevent it from ever being
>>> instantiated.
>>
>> I don't think that's actually possible:
>>
>> Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
>> (Intel)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>>
>>>>> class Foo:
>>
>> ...     def __new__(cls):
>> ...         raise TypeError
>> ...     def __init__(self):
>> ...         raise TypeError
>> ...
>>>>>
>>>>> type(object.__new__(Foo))
>>
>> <class '__main__.Foo'>
>
>
> Try:
>
> class Foo(object):
>    def __new__(cls):
>        return cls


Okay:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __new__(cls):
...         return cls
...
>>> f1 = object.__new__(Foo)
>>> f2 = object.__new__(Foo)
>>> type(f1), type(f2)
(<class '__main__.Foo'>, <class '__main__.Foo'>)
>>> f1 is f2
False



More information about the Python-list mailing list