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?
__new__ returns a instance of class. __init__ receives the instances of the class returned by __new__ . Use __init__ to initilize value.
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.
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.
__init__ : This method called when an object is created from the class and it allow the class to initialize the attributes of a class.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With