測試環境為 CentOS 8 x86_64 (虛擬機)
下面來看一下 __init__ & __call__ 的使用時機.
- object.__init__(self[, …]) – https://docs.python.org/3/reference/datamodel.html#object.__init__
Called after the instance has been created (by __new__()) - object.__call__(self[, args…]) – https://docs.python.org/3/reference/datamodel.html#object.__call__
Called when the instance is “called” as a function.
參考文章 – https://vimsky.com/zh-tw/examples/usage/__call__-in-python.html
- 範例 :
[root@localhost ~]# vi call.py class Product: def __init__(self): print("Instance Created") def __call__(self, a, b): print(a * b) ans = Product() ans(10, 20)
執行結果
[root@localhost ~]# python3 call.py Instance Created 200
說明:
在建立 Instance 時就會去呼叫 __init__ (初始化函式).ans = Product()
執行結果
Instance Created
當 Instance 作為函數時使用就會去呼叫 __call__ 涵式.
ans(10, 20)
執行結果
200
沒有解決問題,試試搜尋本站其他內容