[整理]類與方法的區別是什么?


以下是stackoverflow上: Difference between a method and a function問題的高票回答。

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed. A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences: A method is implicitly passed the object on which it was called. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data). (this is a simplified explanation, ignoring issues of scope etc.)

翻譯以下就是:

函數是一段代碼,通過名字來進行調用。它能將一些數據(參數)傳遞進去進行處理,然后返回一些數據(返回值),也可以沒有返回值。
所有傳遞給函數的數據都是顯式傳遞的。方法也是一段代碼,也通過名字來進行調用,但它跟一個對象相關聯。
方法和函數大致上是相同的,但有兩個主要的不同之處:
方法中的數據是隱式傳遞的;方法可以操作類內部的數據(請記住,對象是類的實例化–類定義了一個數據類型,而對象是該數據類型的一個實例化)
以上只是簡略的解釋,忽略了作用域之類的問題。

《Python基礎教程》中講到:

類的方法與普通的函數只有一個特別的區別——它們必須有一個額外的第一個參數名稱,但是在調用這個方法的時候你不為這個參數賦值,Python會提供這個值。這個特別的變量指對象本身,按照慣例它的名稱是self


免責聲明!

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



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