python中特殊方法的调用


新式类( new class )内建特殊方法,和实例的属性字典相互隔离

调用过程不会从 a.__dict__ 中寻找属性,而是从 tyee(a).__dict__ 中寻找属性

For new-style classes 新式类, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

That behaviour is the reason why the following code raises an exception (unlike the equivalent example with old-style classes)

class C(object):
    pass


c = C()
c.__len__ = lambda: 5
len(c)

# Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
# TypeError: object of type 'C' has no len()

__call__方法来说明


class A(object):
    def __call__(self, *args, **kwargs):
        print("invoking __call__ from A!")
        

if __name__ == '__main__':
    a = A()
    a()
    #  output: invoking __call__ from A
    # 这里的调用会使用 A 类的方法 __call__
    
    
    a.__call__ = lambda: "invoking __call__ from lambda!"
    # 在a 对象字典中加入 __call__ 属性
    a.__call__()
    # output:invoking __call__ from lambda
    a()
    # output:invoking __call__ from A!
    # 调用会从 type(a).__dict__ 中寻找属性, 而不是对象的字典中
    
    

Buy me a 肥仔水!