Python中Function(函数)和method(方法)
在Python中,對這兩個東西有明確的規定:
函數function —— A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body.
方法method —— A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self).
從定義的角度上看,我們知道函數(function)就相當于一個數學公式,它理論上不與其它東西關系,它只需要相關的參數就可以。所以普通的在module中定義的稱謂函數是很有道理的。
那么方法的意思就很明確了,它是與某個對象相互關聯的,也就是說它的實現與某個對象有關聯關系。這就是方法。雖然它的定義方式和函數是一樣的。也就是說,在Class定義的函數就是方法。
從上面的角度看似乎很有道理。
>>> def fun():
pass
>>> type(fun)
<class 'function'> #沒有問題
>>> class Cla():
def fun():
pass
@classmethod
def fun1(cls):
pass
@staticmethod
def fun2():
pass
>>> i=Cla()
>>> Cla.fun.__class__
<class 'function'> #為什么還是函數
>>> i.fun.__class__ #這個還像話
<class 'method'>
>>> type(Cla.fun1)
<class 'method'> #這里又是方法
>>> type(i.fun1)
<class 'method'> #這里仍然是方法
>>> type(Cla.fun2)
<class 'function'> #這里卻是函數
>>> type(i.fun2)
<class 'function'> #這里卻是函數
事實上,上面的結果是可以解釋的:
1,普通方法(老版中直接就是"instancemethod")在module中與在Class中定義的普通函數,從其本身而言是沒有什么區別的,他們都是對象函數屬性。 之所以會被說在Class中的定義的函數被稱為方法,是因為它本來就是面向將來的實例對象的,其實他們就是實例方法,這些方法是與實例相聯系的(從實例出發訪問該函數會自動賦值)。所以你從Class訪問仍然是一個函數
2,類方法("classmethod"),因為類同樣是對象,所以如果函數與類進行聯系了話(與實例方法一樣的模式)那么就能夠這么說了!
3,靜態方法,雖然定義在內部,并且也較方法,但是卻不與任何對象聯系,與從類訪問方法是一樣的,他們仍然是函數。
這樣看來上面的定義可以改改了:
函數的定義自然不變。
方法的定義可以是這樣的,與某個對象進行綁定使用的函數。注意哦。綁定不是指" . "這個符號,這個符號說實在的只有域名的作用。綁定在這里是指,會默認賦值該綁定的對象。
總結
以上是生活随笔為你收集整理的Python中Function(函数)和method(方法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用eval在txt中存储list,dic
- 下一篇: 全面解析python类的绑定方法与非绑定