python3 __call__方法


刷面試題看到的,沒看懂這個方法有什么實際用途,官方文檔如下:

3.3.6. Emulating callable objects

object. __call__ (self[, args...])
   Called when the instance is “called” as a function; if this method is defined,  x(arg1, arg2, ...)  is a shorthand for  x.__call__(arg1, arg2, ...) .

主要實現的是將類的對象當作函數直接調用

例如:

class Demo(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def my_print(self,):
        print("a = ", self.a, "b = ", self.b)

    def __call__(self, *args, **kwargs):
        self.a = args[0]
        self.b = args[1]
        print("call: a = ", self.a, "b = ", self.b)

if __name__ == "__main__":
    demo = Demo(10, 20)
    demo.my_print()

    demo(50, 60)
結果如下:
a =  10 b =  20
call: a =  50 b =  60

 需要注意的是:只有當在類中定義了 def __call__() 方法后,才可以實現這個功能,否則會出現語法錯誤,就是文檔中解釋的 if this method is defined 的意思。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM