What is a Callable?
What is a Callable?
In Python, a "callable" refers to any object that can be called using a pair of parentheses, potentially with arguments. The concept of callables is integral to understanding how Python handles functions, methods, and other objects that execute or trigger code.
def
keyword, functions can accept arguments and return values.__call__()
method, its instances become callable. This method is executed when the instance is "called" as if it were a function.__call__()
MethodThe __call__()
method in Python allows an instance of a class to be called as if it were a function. If you define this method in a class, you can execute custom behavior directly on the instances. For example:
class Adder:
def __init__(self, value):
self.value = value
def __call__(self, x):
return self.value + x
add_five = Adder(5)
result = add_five(10) # Calls the __call__ method, result is 15
To determine whether an object is callable, Python provides a built-in function callable()
, which returns True
if the object appears callable and False
otherwise. This function is useful for checking if an object can be called without causing an error due to inapprop...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào