What is a “callable”?

前端 未结 12 2091
谎友^
谎友^ 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:09

    A callable is anything that can be called.

    The built-in callable (PyCallable_Check in objects.c) checks if the argument is either:

    • an instance of a class with a __call__ method or
    • is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.)

    The method named __call__ is (according to the documentation)

    Called when the instance is ''called'' as a function

    Example

    class Foo:
      def __call__(self):
        print 'called'
    
    foo_instance = Foo()
    foo_instance() #this is calling the __call__ method
    

提交回复
热议问题