Understanding Python_magic method__call__

Overview:

Python has a lot of built-in magic methods, usually represented by double underscores at the beginning and end. For example, __name__, __doc__, __new__, __init__, __call__, etc. These magic methods will make objects hold special behaviors. Today, I will introduce the __call__ that I usually use more, and I call it: instance magic method.

How to use

What is an instance magic method? , that is, it can call the class instance as a function.

take a chestnut

class Bar:
    def __call__(self, *args, **kwargs):
        print('i am instance method')

b = Bar()  # 实例化
b()  # 实例对象b 可以作为函数调用 等同于b.__call__ 使用


# OUT: i am instance method



# 带参数的类装饰器
class Bar:

    def __init__(self, p1):
        self.p1 = p1

    def __call__(self, func):
        def wrapper():
            print("Starting", func.__name__)
            print("p1=", self.p1)
            func()
            print("Ending", func.__name__)
        return wrapper


@Bar("foo bar")
def hello():
    print("Hello")

# 上面的语法糖写法 等价于 hello = Bar('foo bar')(hello)

if __name__ == "__main__":
    hello()

#OUT
    Starting hello
    p1= foo bar
    Hello
    Ending hello

implement

The instance becomes a callable object, which is consistent with the ordinary function, and the logic executed is the internal logic of the call function.

advantage

  • When the code logic is very complex, it is not suitable to be written in a function, and it will be encapsulated into a class. When calling an object of this class, we directly use the instance as a function reference, which is more convenient and concise.
  • Implement class decorators with call .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325472515&siteId=291194637