在 Python 函式和 Python 物件方法之間,哪個更基礎?
函式是 Python 中的可呼叫物件,即可以使用呼叫運算子進行呼叫。但是,其他物件也可以透過實現 __call__ 方法來模擬函式。
示例
def a(): pass # a() is an example of function print a print type(a)
輸出
C:/Users/TutorialsPoint/~.py <function a at 0x0000000005765C18> <type 'function'>
方法是一種特殊的函式,可以是繫結或未繫結的。
示例
class C: def c(self): pass print C.c # example of unbound method print type(C.c) print C().c # example of bound method print type(C().c) print C.c()
當然,未繫結的方法在不傳遞引數的情況下無法呼叫。
輸出
<function a at 0xb741b5a4> <type 'function'> <unbound method C.c> <type 'instancemethod'> <bound method C.c of <__main__.C instance at 0xb71ade0c>> <type 'instancemethod'> Traceback (most recent call last): File "~.py", line 11, in <module> print C.c() TypeError: unbound method c() must be called with C instance as first argument (got nothing instead)
在 Python 中,繫結方法、函式或可呼叫物件(即實現了 __call__ 方法的物件)或類建構函式之間沒有太大區別。它們看起來都一樣,只是命名約定不同,儘管在底層可能看起來大不相同。
這意味著繫結方法可以用作函式,這是使 Python 如此強大的眾多小特性之一。
>>> d = A().a #this is a bound method of A() >>> d() # this is a function
這也意味著,儘管 len(...) 和 str(...) 之間存在根本區別(str 是型別建構函式),但我們直到深入一點才會注意到這種區別。
>>>len <built-in function len> >>> str <type 'str'>
廣告