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.
__new__ is a static method, not a class method.
__new__ returns a instance of class. __init__ receives the instances of the class returned by __new__ . Use __init__ to initilize value.
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.
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.
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.
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