Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Python) __new__ method returning something other than class instance

Tags:

python

Is it possible, and if it is, then how to do so, that creating a new object of a class returns something other than the object itself?

Suppose, I want every newly created object to start out as a list consisting of itself.

>> class A:
      *magic*

>> a = A()
>> print a

[<__main__.A instance at 0x01234567>]

Probably it can be done by overriding the __new__ method in some way, but how?

like image 443
user2649762 Avatar asked Nov 26 '13 15:11

user2649762


People also ask

What should __ new __ return?

__new__ returns a instance of class. __init__ receives the instances of the class returned by __new__ . Use __init__ to initilize value.

What does the __ New__ method do in Python?

The __new__() is a static method of the object class. When you create a new object by calling the class, Python calls the __new__() method to create the object first and then calls the __init__() method to initialize the object's attributes.

What is __ instance in Python?

An instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function, __init__(self,..) of the class.

What is the purpose of the magic method __ init __?

__init__ : This method called when an object is created from the class and it allow the class to initialize the attributes of a class.


1 Answers

Yes, __new__ can return something else than the new instance:

class A(object):
    def __new__(cls, *args, **kw):
        instance = super(A, cls).__new__(cls, *args, **kw)
        return [instance]

Demo:

>>> class A(object):
...     def __new__(cls, *args, **kw):
...         instance = super(A, cls).__new__(cls, *args, **kw)
...         return [instance]
... 
>>> A()
[<__main__.A object at 0x10f33f390>]

Note that __init__ is not called if the returned object is not the same type (so isinstance(returned_value, A) is False); that means that a custom A.__init__() is never going to be called here! Call it explicitly:

class A(object):
    def __new__(cls, *args, **kw):
        instance = super(A, cls).__new__(cls, *args, **kw)
        if hasattr(cls, '__init__'):
            instance.__init__(*args, **kw)            
        return [instance]
like image 122
Martijn Pieters Avatar answered Sep 24 '22 19:09

Martijn Pieters