提示信息

Python __call__()

思慕 已关注

The __call__() method in Python is a special method that allows an object to be callable like a function. When the __call__() method is defined inside a class, instances of that class can be called as if they were functions.

Here is an example to illustrate the usage of __call__() method:

  1. class Foo:
  2. def __init__(self):
  3. self.counter = 0
  4. def __call__(self):
  5. self.counter += 1
  6. print(f"Instance called {self.counter} times")
  7. foo = Foo()
  8. foo() # This will print: "Instance called 1 times"
  9. foo() # This will print: "Instance called 2 times"

In this example, the Foo class has a __call__() method defined. The method increments the counter attribute each time it is called and prints the value of counter. Instances of the Foo class can be called as if they were functions, and each call will increment the counter attribute and print the updated value.

The __call__() method can also accept arguments and return a value, just like regular functions.

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
思慕 关注 已关注

最近一次登录:2023-10-09 16:05:53   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图