Pin-Jiun / Python

Python Document
0 stars 0 forks source link

37-object __call__() #38

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

Python has a set of built-in methods and call is one of them. The call method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.call(arg1, arg2, ...).

call()可以使code更簡潔,不用再新增額外的methon去表達

object() is shorthand for object.__call__()
class Example:
    def __init__(self):
        print("Instance Created")

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

# Instance created
e = Example()

# __call__ method will be called
e()
Instance Created
Instance is called via special method
class Product:
    def __init__(self):
        print("Instance Created")

    # Defining __call__ method
    def __call__(self, a, b):
        print(a * b)

# Instance created
ans = Product()

# __call__ method will be called
ans(10, 20)
Instance Created
200

https://www.geeksforgeeks.org/__call__-in-python/