Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using __new__ in python

I am new to python and trying my hand at classes. I do understand the difference between __init__ and __new__. Here is a snippet of my class,

class Vector2D:

    def __new__(cls):
        print "Testing new"
        return super(Vector2D,cls).__new__(cls)

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return "X:" + str(self.x) + ",Y:" + str(self.y)

I am initializing the class like below and expecting "Testing new" to be printed first:

def Main():
    vec = Vector2D(1,2)
    print "Printing vec:",vec

but I am only getting the output,

Printing vec: X:1,Y:2

What do I have to do in the method __new__() for "Testing new" to be printed?

Thank you.

like image 385
Ayubx Avatar asked Mar 03 '16 11:03

Ayubx


People also ask

Is __ new __ a class method?

__new__ is a static method, not a class method.

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.

How does __ add __ work in Python?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1. __add__(obj2). This works, because int implements the __add__() method behind the scenes.

What is __ add __?

Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator “+” in Python.


1 Answers

You have to make your Vector2D class a subclass of object otherwise a lot of things won't work properly. The things that won't work include __new__ and super.

This should work just fine:

class Vector2D(object):
    def __new__(cls, *args, **kw):
        print "Testing new"
        return super(Vector2D,cls).__new__(cls)


    def __init__(self, x, y):
        self.x = x
        self.y = y


    def __str__(self):
        return "X:" + str(self.x) + ",Y:" + str(self.y)

Note that the arguments used when you construct the instance are passed both to __new__ and __init__ so you have to be prepared to accept them in __new__, but your superclass (object) doesn't take any parameters in its __new__ method so don't pass them up the chain.

like image 192
Duncan Avatar answered Sep 22 '22 07:09

Duncan