Why do we have callable objects in python?

后端 未结 3 656
感情败类
感情败类 2020-12-16 00:53

What is the purpose of a callable object? What problems do they solve?

3条回答
  •  有刺的猬
    2020-12-16 01:45

    Many kinds of objects are callable in Python, and they can serve many purposes:

    • functions are callable, and they may carry along a "closure" from an outer function
    • classes are callable, and calling a class gets you an instance of that class
    • methods are callable, for function-like behavior specifically pertaining to an instance
    • staticmethods and classmethods are callable, for method-like functionality when the functionality pertains to "a whole class" in some sense (staticmethods' usefulness is dubious, since a classmethod could do just as well;-)
    • generators are callable, and calling a generator gets you an iterator object
    • finally, and this may be specifically what you were asking about (not realizing that all of the above are objects too...!!!), you can code a class whose instances are callable: this is often the simplest way to have calls that update an instance's state as well as depend on it (though a function with a suitable closure, and a bound method, offer alternatives, a callable instance is the one way to go when you need to perform both calling and some other specific operation on the same object: for example, an object you want to be able to call but also apply indexing to had better be an instance of a class that's both callable and indexable;-).

    A great range of examples of the kind of "problems they solve" is offered by Python's standard library, which has many cases of each of the specific types I mention above.

提交回复
热议问题