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'>

更新於:2020年2月13日

瀏覽量:109

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告