Why does Python use 'magic methods'?

后端 未结 7 1633
既然无缘
既然无缘 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:59

    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:

    • overloaded operators (exist in C++ and others)
    • constructor/destructor
    • hooks for accessing attributes
    • tools for metaprogramming

    and so on...

    0 讨论(0)
提交回复
热议问题