What is a “callable”?

前端 未结 12 2104
谎友^
谎友^ 2020-11-22 01:23

Now that it\'s clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means.

I suppose everybody made once

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 02:05

    Let me explain backwards:

    Consider this...

    foo()
    

    ... as syntactic sugar for:

    foo.__call__()
    

    Where foo can be any object that responds to __call__. When I say any object, I mean it: built-in types, your own classes and their instances.

    In the case of built-in types, when you write:

    int('10')
    unicode(10)
    

    You're essentially doing:

    int.__call__('10')
    unicode.__call__(10)
    

    That's also why you don't have foo = new int in Python: you just make the class object return an instance of it on __call__. The way Python solves this is very elegant in my opinion.

提交回复
热议问题