Why does Python use 'magic methods'?

后端 未结 7 1673
既然无缘
既然无缘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 17:48

    Some of these functions do more than a single method would be able to implement (without abstract methods on a superclass). For instance bool() acts kind of like this:

    def bool(obj):
        if hasattr(obj, '__nonzero__'):
            return bool(obj.__nonzero__())
        elif hasattr(obj, '__len__'):
            if obj.__len__():
                return True
            else:
                return False
        return True
    

    You can also be 100% sure that bool() will always return True or False; if you relied on a method you couldn't be entirely sure what you'd get back.

    Some other functions that have relatively complicated implementations (more complicated than the underlying magic methods are likely to be) are iter() and cmp(), and all the attribute methods (getattr, setattr and delattr). Things like int also access magic methods when doing coercion (you can implement __int__), but do double duty as types. len(obj) is actually the one case where I don't believe it's ever different from obj.__len__().

提交回复
热议问题