I've been playing around with Python recently, and one thing I'm finding a bit odd is the extensive use of 'magic methods', e.g. to make its length available, an object implements a method, def __len__(self)
, and then it is called when you write len(obj)
.
I was just wondering why objects don't simply define a len(self)
method and have it called directly as a member of the object, e.g. obj.len()
? I'm sure there must be good reasons for Python doing it the way it does, but as a newbie I haven't worked out what they are yet.
Changing Built-in Behavior using Magic MethodsMagic methods can enrich our class design by giving us access to Python's built-in syntax features. Python lets our classes inherit from built-in classes. An inheriting child class of a built-in shares all the same attributes, including methods as the built-in.
Magic methods are special methods in python that have double underscores (dunder) on both sides of the method name. Magic methods are predominantly used for operator overloading.
A method in python is somewhat similar to a function, except it is associated with object/classes. Methods in python are very similar to functions except for two major differences. The method is implicitly used for an object for which it is called. The method is accessible to data that is contained within the class.
A dunder method acts as a contract between the Python interpreter and the person who made a particular Python class. The person who made the int class defined the __add__ method to let Python know that the + symbol works on int objects. Addition relies on a dunder method, but so do many other operations.
AFAIK, len
is special in this respect and has historical roots.
Here's a quote from the FAQ:
Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
The major reason is history. Functions were used for those operations that were generic for a group of types and which were intended to work even for objects that didn’t have methods at all (e.g. tuples). It is also convenient to have a function that can readily be applied to an amorphous collection of objects when you use the functional features of Python (map(), apply() et al).
In fact, implementing len(), max(), min() as a built-in function is actually less code than implementing them as methods for each type. One can quibble about individual cases but it’s a part of Python, and it’s too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.
The other "magical methods" (actually called special method in the Python folklore) make lots of sense, and similar functionality exists in other languages. They're mostly used for code that gets called implicitly when special syntax is used.
For example:
and so on...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With