Câu hỏi phỏng vấn Python
Câu hỏi

What is a Callable?

Câu trả lời

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.

Types of Callables

  1. Functions: These are perhaps the most straightforward callables. Defined using the def keyword, functions can accept arguments and return values.
  2. Methods: Functions that are defined within a class and operate on instances of that class are called methods. They are callable because they can be invoked on class instances.
  3. Classes: When a class is called, it typically constructs an instance of the class. This is made possible because classes are callable.
  4. Instances of Classes: If a class defines a __call__() method, its instances become callable. This method is executed when the instance is "called" as if it were a function.

The __call__() Method

The __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

Checking Callability

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

middle

Gợi ý câu hỏi phỏng vấn

middle

Is it possible to have static methods in Python?

expert

Is there a simple, elegant way to define singletons?

senior

How is set() implemented internally?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào