Python通过对象名调用方法(对象名后加括号和参数)

Python通过对象名调用方法(对象名后加括号和参数)

提前一周写完软件构造实验,hhh,打算把python捡一捡
然后网上一个例子给看懵了

model = MNIST()  # 声明一个对象
a = model(b)     # 用对象去调用方法????????

小朋友你是不是有很多问号?

一顿搜索
发现其实原因就在于这个类实现了call()方法

可调用对象

可调用对象(callable),我们平时自定义的函数、内置函数和类都属于可调用对象,但凡是可以把一对括号()应用到某个对象身上都可称之为可调用对象,判断对象是否为可调用对象可以用函数 callable

如果在类中实现了 __call__ 方法,那么实例对象也将成为一个可调用对象,

举个栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Entity:
'''调用实体来改变实体的位置。'''

def __init__(self, size, x, y):
self.x, self.y = x, y
self.size = size

def __call__(self, x, y):
'''改变实体的位置'''
self.x, self.y = x, y

e = Entity(1, 2, 3) // 创建实例
e(4, 5) //实例可以象函数那样执行,并传入x y值,修改对象的x y

e(4,5)本质其实是e.__call__(4,5)
所以

__call__ 在那些类的实例经常改变状态的时候会非常有效。
更多厉害的用法可以参考Python call详解

#
You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×