在Python中重载标准parantheses("(()")

Gad*_*i A 2 python operator-overloading

这应该是非常简单但我没有谷歌它:如何(如果有的话)我可以重载Python中的parantheses运算符?这样代码才有意义:

my_new_object = my_new_class()
x = my_new_object(5)
Run Code Online (Sandbox Code Playgroud)

Pra*_*ota 12

你需要__call__在你的课上定义.

例如

>>> class Multiplier(object):
...    def __init__(self, num):
...        self.num = num
...    def __call__(self, other):
...        return self.num*other
...
>>> mul5 = Multiplier(5)
>>> mul5(6)
30
Run Code Online (Sandbox Code Playgroud)


Sve*_*ach 8

定义__call__()你的课程:

class MyNewClass(object):
    def __call__(self, x):
        return x
Run Code Online (Sandbox Code Playgroud)


Bru*_*uno 5

您应该查看本文档的"可调用类型"部分.特别是,你的班级可以实施__call__.