0
better explanation about magic method ?
i still don't understood about magic method in python, when or on what condition u will use it, have anybody got a better expalantion on this, or better reference about magic method ?
1 Resposta
+ 1
It is not one magic method! There are a bunch of methods that are called magic methods. These are the methods that have double underscore around them and can be used to alter the way Python work with your object.
Let's say you define a class, and want the Python interpreter to know how it should delete an object from this class. For example, I want to know how many times I deleted an object from that particular class. Python interpreter already know how to delete an arbitrary object, it just releases the ram associated with the object. But we want it to do more. Here is when we should use the magic method for deleting the object. __del__() is the method. We can define this method in the body of the class, and in the definition, add to our counter and then call the python delete mechanism.
Another way of using a magic method is using the constructor for the class. __init__(). When the object is being created, this method is what the interpreter call to make the object. So we can pass the argument of the object to this method, and make our object accordingly. For example, we wrote a rectangle class, and based on the arguments ( the length of the sides.) we want to change the type of it, if it has equal values for the sides, we call it a square. __init__() is the method that initializes all this and this method is the one to change.
Another use of magic methods is operator overloading which I think is covered pretty well in the course.