Chapter 12 Classes
12.5 Special Methods¶
The constructor __init__ is a special method, called automatically when a new object is constructed. In addition to this method, Python provides a number of other special methods, which are called automatically, and the names of which begin and end with two consecutive underscore characters (i.e. ‘__’). For example, __str__ is a special method that is called automatically when string conversion of the object is performed. It must take no arguments (except for self) and returns a string object that represents the object. For an object x, the built-in function call str(x) invokes the method call x.__str__(), and returns its return value. If the method __str__ is not defined in the class of x, str(x) returns a default string representation of x. For example:
Like all methods, the __str__ method can access the attributes of the object via the self argument. The example below shows how a __str__ method can be defined in the Account class, so that information of a specific account can be printed conveniently.
In the example, __str__ accesses attributes through the argument self. Note that the order in which methods are defined in a class is not important. When the class statement is executed, the methods of the class are defined by the execution of def statements, but not executed. The order of method definition in a class statement has no correlation with the order of method execution. During the life cycle of an object, the __init__ method is called first, but then methods can be called in arbitrary orders.
Another special method is __call__(self, [,args]), which is called when the object is called as a function. For example, when the function call expression x(arg1, arg2, arg3) is evaluated, x.__call__(arg1, arg2, arg3) is called automatically, with the return value being used for the return value of the x function call.
© Copyright 2024 GS Ng.