I encounter an example of 'class' when learning about str.format_map()
(Python String format_map())
class Coordinate(dict):
def __missing__(self, key):
return key
Try arguments:
In [25]: Coordinate(x='6')
Out[25]: {'x': '6'}
In [26]: Coordinate(x='6', y='7')
Out[26]: {'x': '6', 'y': '7'}
The hard part to understand is that neitherx=6
is a dict
nor {'x': '6'}
a key.
In official documentation, it specifies:
object.__missing__(self, key)
Called bydict.__getitem__()
to implementself[key]
for dict subclasses when key is not in the dictionary.
It's even more difficult than the previous sample code. There are also good answers here.
The last answer obtain 258 upvotes which frustrates me very much because I get no idea about it. Could it be understood with basic knowledge of python?