Special methods in Python
Introduction
This is a continuation of the article
«Classes»
from the section
«OOP in Python»
.
Knowledge from the following articles will help you understand this material better:
Methods
,
Class methods
,
Static methods
,
super()
,
Decorators
,
isinstance()
Special methods are always surrounded by two underscores on the left and on the right.
We have already come across the special method
__init__()
In the English-speaking community this spelling is usually pronounced as “dunder init”
Example
Let's create an Employee class and see what the repr and str methods show
class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@kaspersky.com' Employee.num_of_emps += 1 def fullname(self): return f'{self.first} {self.last}' def apply_raise(self): self.pay = int(self.pay * self.raise_amount) emp_1 = Employee("Eugene", "Kaspersky", 50000) print(emp_1) print(repr(emp_1)) print(str(emp_1)) # Same as # print(emp_1.__repr__()) # print(emp_1.__str__())
python special_methods.py
<__main__.Employee object at 0x7f486bee5fd0> <__main__.Employee object at 0x7f486bee5fd0> <__main__.Employee object at 0x7f486bee5fd0>
As can be seen from the output above, the methods work and return the same information: that this is an object of the Employee class located at this address.
__repr__()
Let's implement the __repr__() method
def __repr__(self): return f"Employee({self.first}, {self.last}, {self.pay})"
python special_methods.py
Employee(Eugene, Kaspersky, 50000) Employee(Eugene, Kaspersky, 50000) Employee(Eugene, Kaspersky, 50000)
Now the information matches what we defined in the method, and again it is the same everywhere.
__str__()
Let's add the __str__() method
def __repr__(self): return f"Employee({self.first}, {self.last}, {self.pay})" def __str__(self): return f"{self.fullname()} - {self.email}"
python special_methods.py
Eugene Kaspersky - Eugene.Kaspersky@kaspersky.com Employee(Eugene, Kaspersky, 50000) Eugene Kaspersky - Eugene.Kaspersky@kaspersky.com
The output of __repr__() has not changed, and print(emp_1) now follows __str__() instead of __repr__()
__add__()
Let's look at the __add__() method
print(1+2) print(int.__add__(1, 2)) print("a" + "b") print(str.__add__("a", "b"))
python special_methods.py
3 3 ab ab
If you try to add two Employee class objects right away, you get TypeError
You can define your own __add__() for any class. In the Employee class you can, for example, add up employee salaries with the following method:
def __add__(self, other): return self.pay + other.pay emp_1 = Employee("Eugene", "Kaspersky", 330) emp_2 = Employee("Andrei", "Olegovich", 330) print(emp_1 + emp_2)
python special_methods.py
660
__repr__() from datetime
Let's study real examples of special methods in use. To do this,
let's look at the library
datetime
(
github
)
Let's start with __repr__()
def __repr__(self): """Convert to formal string, for repr(). >>> dt = datetime(2010, 1, 1) >>> repr(dt) 'datetime.datetime(2010, 1, 1, 0, 0)' >>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc) >>> repr(dt) 'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)' """ return "%s.%s(%d, %d, %d)" % (self.__class__.__module__, self.__class__.__qualname__, self._year, self._month, self._day) # XXX These shouldn't depend on time.localtime(), because that # clips the usable dates to [1970 .. 2038). At least ctime() is # easily done without using strftime() -- that's better too because # strftime("%c", ...) is locale specific.
__str__() from datetime
Let's look at the special method
__str__()
and the library
datetime
(
github
)
The __str__() method simply repeats the isoformat() method
def isoformat(self): """Return the date formatted according to ISO. This is 'YYYY-MM-DD'. References: - http://www.w3.org/TR/NOTE-datetime - http://www.cl.cam.ac.uk/~mgk25/iso-time.html """ return "%04d-%02d-%02d" % (self._year, self._month, self._day) __str__ = isoformat
__add__() from datetime
Let's look at the special method __add__() and the library datetime ( github )
def __add__(self, other): if isinstance(other, timedelta): # for CPython compatibility, we cannot use # our __class__ here, but need a real timedelta return timedelta(self._days + other._days, self._seconds + other._seconds, self._microseconds + other._microseconds) return NotImplemented
Article author: Andrei Olegovich