DFP40203 Python Chapter3 Part5 Magic v2.0
DFP40203 Python Chapter3 Part5 Magic v2.0
PA RT F I V E
3 . 5 U s e M a g i c m et h o d s o f P y t h o n c l a s s e s
3.5.1 Describe Magic methods
3.5.2 Use Magic Method of Python
3.5.1 Describe Magic methods.
Python - Magic Methods
Magic methods in Python are the special methods which add "magic" to your class. It’s always
surrounded by double underscores (e.g. __init__ or __lt__).
Magic methods are not meant to be invoked directly by you, but the invocation happens
internally from the class on a certain action. For example, when two numbers added using the +
operator, internally, the __add__() method will be called.
3.5.2 Use Magic Method of Python Classes
Python - Magic Methods
Magic methods in Python are the special methods which add "magic" to your class. It’s always
surrounded by double underscores (e.g. __init__ or __lt__).
Magic methods are not meant to be invoked directly by you, but the invocation happens
internally from the class on a certain action. For example, when two numbers added using the +
operator, internally, the __add__() method will be called.
Dir() Function
Use the dir() function to see the number of magic methods inherited by a class. For example,
the following lists all the attributes and methods defined in the int class.
Example use magic method to add two numbers using the + operator.
1) Program above show num+10, the + operator calls the __add__(10) method. Then, if call
num.__add__(5) directly also will give the same result. However, as mentioned before, magic
methods are not meant to be called directly, but internally, through some other methods or actions.
2) Magic methods are most frequently used to define overloaded behaviours of predefined
operators in Python. For instance, arithmetic operators by default operate upon numeric operands.
This means that numeric objects must be used along with operators like +, -, *, /, etc. The + operator
is also defined as a concatenation operator in string, list and tuple classes. We can say that the +
operator is overloaded.
3) In order to make the overloaded behaviour available in your own custom class, the corresponding
magic method should be overridden. For example, in order to use the + operator with objects of a
user-defined class, it should include the __add__() method.
__new__() method
1) __new__() magic method is implicitly called before the __init__() method. The __new__()
method returns a new object, which is then initialized by __init__().
When you create an instance of the Employee class, this output come out.
__str__() method
1) It is overridden to return a printable string representation of any user defined class.
the __str__() method in