Sunday, 11 October 2015

Explain how __new__ is a static method in python.

Method signature of __new__

__new__ receives the class whose instance need to be created as the first argument. This statement could be a little confusing, just continue reading and see the next example and again read it after seeing the example, it will be clear. The other arguments received by __new__ are same as what were passed while calling the class.
So, __new__ receives all the arguments that we pass while calling the class. Also, it receives one extra argument. This extra argument is the class whose instance need to be created and it will be received as first argument by __new__.
So, signature of __new__ could be written as:
__new__(cls, *args, **kwargs)

As i could understand it, __new__ is a static method.
Please see:
http://docs.python.org/referen...
We can use super within new. We could have written "new_instance = super(A, cls).__new__(cls, *args, **kwargs)"
in place of
"new_instance = object.__new__(cls, *args, **kwargs)".
For class methods, calling the method on the class implicitly sends the current class as the first argument. An example:
class A(object):
@classmethod
def met(cls, a):
print a
We can call this method on the class passing it only one argument and the class will implicitly be sent as the first argument.
A.met(5)
This works.
But when we override __new__, we have to explicitly send cls received in the overridden __new__ as the first argument. I mean we need to write:
super(A, cls).__new__(cls, *args, **kwargs)
Had it been a class method, this would have worked:
super(A, cls).__new__(*args, **kwargs)
because the class on which it were called would have been implicitly passed as first argument since it were a class method. But it doesn't work.
That's why i feel its a static method.
for more detail about __new__ go to this link how object creates in python
Let me know if i am wrong somewhere.
for more  deep details visit the site http://agiliq.com/blog/2012/06/__new__-python/

16 comments:

  1. Just to add clarification, because I've seen people elsewhere confused about this: When Bharti says

    > Had it been a class method, this would have worked:
    >
    > super(A, cls).__new__(*args, **kwargs)
    >
    > because the class on which it were called would have been implicitly passed as first argument since it were a class method. But it doesn't work.

    They mean that Foo.some_class_method(x, y) passes (Foo, x, y) as the arguments to some_class_method. So, for super(A, cls).__new__(*args, **kwargs), we'd wind up passing (super(A, cls), *args, **kwargs) rather than (cls, *args, **kwargs), which is _not_ what we want.

    ReplyDelete