python类中的__call__
时间: 2023-07-03 10:24:14 浏览: 54
在 Python 中,类可以定义一个名为 `__call__` 的特殊方法,使用这个方法可以使得类的实例对象可以像函数一样被调用。当使用类的实例对象像函数一样被调用时,实际上是调用了 `__call__` 方法。在 `__call__` 方法中可以编写类似函数的逻辑。
例如,我们可以定义一个类,实现一个简单的计数器,每次调用这个类的实例对象时,计数器加 1:
```python
class Counter:
def __init__(self):
self.count = 0
def __call__(self):
self.count += 1
return self.count
```
然后我们可以创建一个 Counter 的实例对象,并像调用函数一样使用它:
```python
counter = Counter()
print(counter()) # 输出 1
print(counter()) # 输出 2
print(counter()) # 输出 3
```
这样可以方便地实现一些需要记忆状态的功能,比如缓存结果、记录历史等等。
相关问题
Python中__call__
在 Python 中,`__call__` 是一个特殊的方法,它可以让一个类的实例像函数一样被调用。当我们在一个类中定义了 `__call__` 方法时,它会被用来实现这个类的实例的调用操作。
例如,我们可以定义一个带有 `__call__` 方法的类 `Adder`,它可以将传入的两个数字相加并返回结果:
```python
class Adder:
def __call__(self, a, b):
return a + b
add = Adder()
result = add(2, 3) # 等同于调用 add.__call__(2, 3)
print(result) # 输出 5
```
在上面的例子中,我们创建了一个 `Adder` 类,并在其中定义了 `__call__` 方法。当我们创建了 `Adder` 类的实例 `add` 后,我们可以像调用函数一样使用它,传入两个参数 `2` 和 `3` 并得到结果 `5`。
需要注意的是,只有在类中定义了 `__call__` 方法时,其实例才能被调用。如果我们尝试在没有定义 `__call__` 方法的类的实例上进行调用操作,Python 解释器会抛出一个 `TypeError` 异常。
python中__call__
在 Python 中,如果一个类定义了__call__方法,那么它的实例就可以像函数一样调用。__call__方法允许对象行为像函数一样,接受参数并返回值。
例如:
```
class Foo:
def __call__(self, *args, **kwargs):
print("Calling the Foo instance")
f = Foo()
f() # prints "Calling the Foo instance"
```
上面的类Foo的实例f就可以像函数一样调用,输出"Calling the Foo instance"
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)