Ayubx
Ayubx

Reputation: 665

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.

Upvotes: 5

Views: 4511

Answers (1)

Duncan
Duncan

Reputation: 95652

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.

Upvotes: 8

Related Questions