Python callable() Function
callable()Is a built-in function in Python used to check whether an object is callable.
In Python, functions, methods, classes, etc., are all callable objects.callable()It can help us check whether an object can be called before calling it, avoiding runtime errors.
Word Definition: callable 意为"可调用的",表示对象是否可以像函数一样被调用。
Basic Syntax and Parameters
Syntax Format
callable(object)
Parameter Description
- Parameter object:
- Type: Any object
- Description: The object to check.
Function Description
- Return value: Returns a boolean value
TrueorFalse。 - Note: Return True does not mean the call will definitely succeed, it just means the object is callable.
Examples
Example 1: Check Various Objects
Example
# Function
def my_func():
pass
print(callable(my_func)) # Output: True
# Method
class MyClass:
def my_method(self):
pass
obj = MyClass()
print(callable(obj.my_method)) # Output: True
# Class (a class can be called to create instances)
print(callable(MyClass)) # Output: True
# Built-in function
print(callable(len)) # Output: True
print(callable(print)) # Output: True
# String (not callable)
print(callable("hello")) # Output: False
# Number (not callable)
print(callable(123)) # Output: False
# Lambda expression
my_lambda = lambda x: x * 2
print(callable(my_lambda)) # Output: True
def my_func():
pass
print(callable(my_func)) # Output: True
# Method
class MyClass:
def my_method(self):
pass
obj = MyClass()
print(callable(obj.my_method)) # Output: True
# Class (a class can be called to create instances)
print(callable(MyClass)) # Output: True
# Built-in function
print(callable(len)) # Output: True
print(callable(print)) # Output: True
# String (not callable)
print(callable("hello")) # Output: False
# Number (not callable)
print(callable(123)) # Output: False
# Lambda expression
my_lambda = lambda x: x * 2
print(callable(my_lambda)) # Output: True
Expected output:
True True True True True False False True
Code analysis:
- Functions, methods, classes, and lambda expressions are all callable.
- Basic types such as strings and numbers are not callable.
Example 2: Practical Application
Example
# Safely call a function
def safe_call(obj, *args, **kwargs):
if callable(obj):
return obj(*args, **kwargs)
else:
return f"{obj} is not callable"
# Test
def greet(name):
return f"Hello, {name}!"
print(safe_call(greet, "Tom")) # Output: Hello, Tom!
print(safe_call("not a function")) # Output: not a function not callable
# Use in API design
class EventHandler:
def __init__(self):
self.handlers = {}
def register(self, event, handler):
if not callable(handler):
raise TypeError("handler must be callable")
self.handlers[event] = handler
def trigger(self, event, *args):
if event in self.handlers:
return self.handlers[event](*args)
handler = EventHandler()
handler.register("click", lambda: "Handle click")
print(handler.trigger("click")) # Output: Handle click
# Registering a non-callable object will raise an error
# handler.register("error", "not callable") # Raises TypeError
def safe_call(obj, *args, **kwargs):
if callable(obj):
return obj(*args, **kwargs)
else:
return f"{obj} is not callable"
# Test
def greet(name):
return f"Hello, {name}!"
print(safe_call(greet, "Tom")) # Output: Hello, Tom!
print(safe_call("not a function")) # Output: not a function not callable
# Use in API design
class EventHandler:
def __init__(self):
self.handlers = {}
def register(self, event, handler):
if not callable(handler):
raise TypeError("handler must be callable")
self.handlers[event] = handler
def trigger(self, event, *args):
if event in self.handlers:
return self.handlers[event](*args)
handler = EventHandler()
handler.register("click", lambda: "Handle click")
print(handler.trigger("click")) # Output: Handle click
# Registering a non-callable object will raise an error
# handler.register("error", "not callable") # Raises TypeError
Expected output:
Hello, Tom! not a function 不可调用 处理点击
callable()It is very useful when you need to dynamically call functions or verify callback functions.
Other Extensions
Python3 Built-in Functions