Reputation: 37
Just like the __init__()
method, do the other special functions get called automatically when I create an object?
Check out this simple class for example:
class Point:
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x,self.y)
Is the __str__()
method called automatically when I create a new object?
Upvotes: 0
Views: 1198
Reputation: 120499
At each time you create an object, the __init__
method is called.
At each time you print an object, the __str__
method is called to get.
class Point:
def __init__(self, x = 0, y = 0):
print('__init__')
self.x = x
self.y = y
def __str__(self):
print('__str__')
return "({0},{1})".format(self.x,self.y)
>>> p = Point(3, 2)
__init__
>>> print(p)
__str__
(3,2)
>>> p
<__main__.Point at 0x7fa3ab341940>
For the last case, the __str__
method is not called but __repr__
. A good practice is to override this method to create a string representation of the creation of the instance like Point(3, 2)
:
def __repr__(self):
print('__repr__')
return f"Point({self.x}, {self.y})"
>>> p = Point(4, 6)
__init__
>>> p
__repr__
Point(4, 6)
Upvotes: 2
Reputation: 16536
No. Magic/special methods are only get called when their time arrives. When you create an instance of your class, your initializer method (__init__
) is get called. when you print your object using print
or when you call str()
function, the __str__
method gets called. So this is in print()
line, not when you create an instance of your class.
Put a simple print statement inside your methods, and run your script in interactive mode to see when which method is gets called.
In interactive mode, if you don't use print
function, you will see that __str__
will not get called. Instead __repr__
is called. since you havn't implement that in your class, you will inherit it from the object
class.
>>> obj = Point()
>>> print(obj)
(0,0)
>>> obj
<__main__.Point object at 0x0000024E0989D940>
>>>
Upvotes: 2