Home > OS >  Do special functions get called every time I create an object?
Do special functions get called every time I create an object?

Time:12-18

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?

CodePudding user response:

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, the __str__ method gets called. 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.

CodePudding user response:

No, it is only called when you do point.__str__(). Only the __init__ function is called when you create the objext.

CodePudding user response:

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>
  • Related