Using __new__ in python

I am new to python and try myself in classes. I 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 initialize the class as shown below and expect that "Testing new" will be printed first:

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

but I only get the conclusion

Printing vec: X:1,Y:2

What do I need to do in the __new__()Test Method of Printing New method ?

Thank.

+4
source share
1 answer

You must make your class a Vector2Dsubclass object, otherwise many of them will not work properly. What will not work includes __new__and super.

This should work 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)

, , , __new__ __init__, __new__, (object) __new__, .

+6

All Articles