Why does Python use 'magic methods'?

后端 未结 7 1657
既然无缘
既然无缘 2020-11-29 16:56

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

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 17:47

    From the Zen of Python:

    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.

    This is one of the reasons - with custom methods, developers would be free to choose a different method name, like getLength(), length(), getlength() or whatsoever. Python enforces strict naming so that the common function len() can be used.

    All operations that are common for many types of objects are put into magic methods, like __nonzero__, __len__ or __repr__. They are mostly optional, though.

    Operator overloading is also done with magic methods (e.g. __le__), so it makes sense to use them for other common operations, too.

提交回复
热议问题