Question:
In Python there are "Magical" methods, such as __len__
, which allows the use of len(object), in addition to this one in particular, what are the most used ones that can facilitate the use of the structure?
Answer:
Special or magic methods in Python are used to define a specific behavior for a class when a certain operation is performed.
For example, there are situations where you can define a behavior when the object of this class is treated as str
or as float
. There are still other cases where you can define behavior when the object is called as a function, whether it is used in comparison operations or mathematical operations. Anyway, Python offers a wide range of special methods so you can customize the behavior of your class.
The list of magic methods that can be used in Python is quite large . So I'll post just a few examples here:
__str__
It is invoked when the object is invoked as str
.
Example:
class MyClass(object):
def __str__(self):
return 'is my class'
obj = MyClass();
print("This " + str(obj))
The result will be: "This is my class"
__call__
It is invoked when the object is invoked as a function.
class MyClass(object):
def __call__(self):
return 'Hello World!'
obj = MyClass();
print(obj())
Result is "Hello World!"
__init__
It is used to initialize the class.
Example:
class Person(object):
def __init__(self, name):
self.name = name
p = Person('Wallace');
print(p.name)
Result: "Wallace"
__float__
When you define this method, your class will have the behavior determined by it when there is an attempt to use the instance of that class as the float
type.
Look:
class Numero(object):
def __float__(self):
return 1.11111
print(float(Numero()))
The result will be: 1.11111
I believe that having examples of __str__
and __float
in my answer, it becomes unnecessary to talk about the existence of __int__
, __bytes__
, __dict__
, since they will work in similar ways for each type.
other methods
There are also several magical methods used to customize comparison operations.
-
__lt__
: Less than (less than) -
__le__
: Less or equal (less or equal) -
__eq__
: Equals (equals) -
__ne__
: Not equal (not equal) -
__ge__
: Greater or equal -
__gt__
: – Greater than (greater than)
All of the above methods are invoked when you use a comparative expression. Generally, they receive a parameter that must be compared with a value of the current class.
__eq__
example:
class Numero(object):
def __init__(self, numero):
self.numero = numero
def __eq__(self, a):
print("Chamou __eq__")
print(a.numero)
a = Numero(1)
b = Numero(2)
a == b
b == a
The result will be:
"Chamou __eq__"
2
"Chamou __eq__"
1
Read more on Standard operators as function