Search code examples
pythoninheritancenew-operatornew-style-class

What happens when you call object.__new__?


  1. Old-style class

    class Person():
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed1 is ahmed2
    print ahmed1
    print ahmed2
    
    
    >>> False
    <__main__.Person instance at 0xb74acf8c>
    <__main__.Person instance at 0xb74ac6cc>
    >>>
    
  2. New-style class

    class Person(object):
        _names_cache = {}
        def __init__(self,name):
            self.name = name
        def __new__(cls,name):
            return cls._names_cache.setdefault(name,object.__new__(cls,name))
    
    ahmed1 = Person("Ahmed")
    ahmed2 = Person("Ahmed")
    print ahmed2 is ahmed1
    print ahmed1
    print ahmed2
    
    >>> True
    <__main__.Person object at 0xb74ac66c>
    <__main__.Person object at 0xb74ac66c>
    >>>
    

I want to understand what happens in the two versions of the code when I call object.__new__?


Solution

  • Old-style classes do not support a __new__ method:

    >>> class Foo:
    ...     def __new__(self, *args, **kw):
    ...         print 'Nope'
    ... 
    >>> Foo()
    <__main__.Foo instance at 0x101f5c908>
    

    __new__ is a new-style class feature only.