class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
v=Vector(2, 3)
print(v)
In above case: how is repr being called when I print v?
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
v=Vector(2, 3)
print(v)
In above case: how is repr being called when I print v?
The __repr__
method is called by the builtin function repr
and is what is echoed on your python shell when it evaluates an expression that returns an object. When you will just print the v
variable it will print the return
of that function. When you will not include the __repr__
you will get <__main__.Vector object at 0x037B2CA0>
where at
is thee place in memory
repr is a special built-in function of python. Basically, whenever python finds this method within the context of an object, it'll print what this function returns when you attempt to print the object as its "representation"!
Built-in functions can commonly be identified by the double underscores on each side.
You can find the other built-in functions here.
This can realize your idea
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return self.__repr__()
def __repr__(self):
return 'Vector(%r, %r)' % (self.x, self.y)
v=Vector(2, 3)
print(v)
And you can learn more from this answer: Difference between __str__ and __repr__?
You may call this method explicitly like this:
In [2]: v.__repr__()
Out[2]: 'Vector(2, 3)'
In [3]: print(v.__repr__())
Vector(2, 3)
In [4]: type(v.__repr__())
Out[4]: str
The main idea behind this - define a method that is called implicitly when you call print(v)
.
There's actually one more function in between (so called build-in function) - repr
(see here). If you don't define __repr__
it will print some default values.
In [1]: class Vector:
...: def __init__(self, x=0, y=0):
...: self.x = x
...: self.y = y
...:
In [2]: v = Vector(2, 3)
In [3]: print(v)
<__main__.Vector object at 0x108e97a60>
So you may control what it returns:
A class can control what this function returns for its instances by defining a
__repr__()
method.