Transforming Your Objects Into ‘Real’ Python Objects Using Magic Methods | by Tomisin Abiodun | Feb, 2022

Learn about the methods behind common Python syntax and how to make your objects work with these constructs.

Tomycin Abiodone
Photo by Julius Drost on Unsplash

Magic methods simply refer to Special methods that start and end with a double underscore. Also called “immersion” methods.

magic methods They are not designed to be called directly, rather they are called internally from the class in a specific action or when strange syntax is encountered.

rendering functions

__new__(self, *args, **kwargs) This is the first step in creating the instance. It is called first and is responsible for back A new instance of your class. Use this method if you want to control how new instances are created.

Display functions

Objects would be completely anonymous without the help of built-in functions that help define and format them in a way that is not only meaningful but also useful during development and testing.

equal signs

These functions are called when the compiler encounters the equal sign between two variables. These include:

Prepare

The most characteristic of numbers are arithmetic operations. We can make our objects display the same behaviors that numbers do and respond to arithmetic symbols as numbers do, simply by implementing one or two of the special methods listed below.

Photo by Matteo Fusco on Unsplash
>>> Temperature(30, 'C') + 1TypeError: unsupported operand type(s) for +: 'Temperature' and 'int'
>>> Temperature(30, 'C') + 6
<Temperature: 36°C>
>>> Temperature(30, 'C') + Temperature(35.6, 'F')
<Temperature: 38°C>
>>> Temperature(34, 'C') + Temperature(66, 'C')
<Temperature: 100°C>

Iterators: lists, groups, strings, groups

__contains__(self, x) This is used when in The keyword is used to check if the element exists in the iterator (eg: x in ["a", "b"])

Real-life Example #2: A more pythonic approach to Scrabble

Let’s bring to life everything we learned in this article with a simplified visualization of Scrabble. Our Scrabble game will use a number of magical techniques to make it interact with the interpreter in a more friendly manner.

Photo by Brett Jordan on Unsplash
tile_a = Tile('A', 1)
tile_q = Tile('Q', 10)
print(tile_a)
# A (1)
print(tile_q)
# Q (10)
print(tile_q > tile_a)
# True
move_one = Move([
[tile_a, cell_1], [tile_c, cell_2], [tile_e, cell3]
])
print(move_one)
# ACE = 5
move_two = Move([
[tile_z, cell_1], [tile_o, cell_2], [tile_o, cell3]
])
print(move_two)
# ZOO = 12
print(move_one > move_two)
# False
print(move_one < move_two)
# True

Large Python projects would definitely be much easier to work with, if they accepted most of their components and responded to a lot of the syntax we’re used to with native types – we see this in the Django ORM, with the ability to iterate much more QueryDict.

Leave a Comment