Python3中__call__方法介绍

x33g5p2x  于2022-01-06 转载在 Python  
字(0.9k)|赞(0)|评价(0)|浏览(257)

    如果Python3类中有__call__方法,那么此类实例的行为类似于函数并且可以像函数一样被调用。当实例作为函数被调用时,如果定义了此方法,则x(arg1, arg2, …)是x.call(arg1, arg2, …)的简写。

**      为了将一个类实例当作函数调用,我们需要在类中实现__call__()**方法。该方法的功能类似于在类中重载()运算符,使得类实例对象可以像调用普通函数那样,以”对象名()”的形式使用。

    以下为测试代码:

var = 2
if var == 1:
    # https://www.geeksforgeeks.org/__call__-in-python/
    class Example:
        def __init__(self):
            print("Instance Created")

        # Defining __call__ method
        def __call__(self):
            print("Instance is called via special method")

    e = Example() # Instance created # __init__ method will be called
    e() # Instance is called via special method # __call__ method will be called
elif var == 2:
    class Product:
        def __init__(self):
            print("Instance Created")

        # Defining __call__ method
        def __call__(self, a, b): # 可以定义任意参数
            print(a * b)

    ans = Product()  # Instance created # __init__ method will be called
    ans(10, 20) # 200 # __call__ method will be called
    ans.__call__(10, 20) # 等价于ans(10, 20)

print("test finish")

    GitHubhttps://github.com/fengbingchun/Python_Test

相关文章