Post

Stephen Gruppetta
Stephen Gruppetta@s_gruppetta·
`.__george__()` In a recent course, a student asked my whether it's possible to create new special methods by using leading and trailing double underscores in the name. No. But you can* define a method with leading and trailing double underscores if you want * you can…but you shouldn't The student's name was George (it still is, technically), so we wrote this dummy class: ``` >>> class SpecialStuff: ... def __george__(self): ... print("There's nothing special to see here!") ... ``` This code "works": ``` >>> stuff = SpecialStuff() >>> stuff.__george__() There's nothing special to see here! ``` So you _can_ define a method with leading and trailing double underscores in its name. But there's nothing special about `.__george__()`. Sorry George, don't take it personally. It's just a normal method. What makes special methods special is not the double underscore syntax–that's just a way to easily identify them. What makes, say, `.__add__()` special is its role within the Python language–Python looks for this method when you use the `+` operator. So, why shouldn't you create methods with leading and trailing double underscores. After all, they look cool? Because you'll confuse everyone else who reads your code. Readability matters. A lot. Someone reading your code might look puzzlingly at the `.__george__()` looks-like-special method. They'll spend hours, days, weeks, years looking for it in the documentation to see what it does behind the scenes in Python… …and do you want to be responsible for these years lost from so many programmers' lives looking for a special method that doesn't exist?
English
1
1
0
220
Monty @ The Python Coding Place
Monty @ The Python Coding Place@ThePythonPlace·
@s_gruppetta I reckon `.__monty__()` should exist as a valid special method—the specialest of all special methods. Who’s with me on this? Let’s start a petition…
English
0
0
0
45
Share