国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

用實例分析Python中method的參數傳遞過程

2020-02-23 00:30:58
字體:
來源:轉載
供稿:網友

什么是method?

function就是可以通過名字可以調用的一段代碼,我們可以傳參數進去,得到返回值。所有的參數都是明確的傳遞過去的。
method是function與對象的結合。我們調用一個方法的時候,有些參數是隱含的傳遞過去的。下文會詳細介紹。
instancemethod
 

In [5]: class Human(object):  ...:   def __init__(self, weight):  ...:     self.weight = weight  ...:   def get_weight(self):  ...:     return self.weight  ...:   In [6]: Human.get_weightOut[6]: <unbound method Human.get_weight>

這告訴我們get_weight是一個沒有被綁定方法,什么叫做未綁定呢?繼續看下去。
 

In [7]: Human.get_weight()---------------------------------------------------------------------------TypeError                 Traceback (most recent call last)/home/yao/learn/insight_python/<ipython-input-7-a2b2c5cd2f8d> in <module>()----> 1 Human.get_weight() TypeError: unbound method get_weight() must be called with Human instance as first argument (got nothing instead)

未綁定的方法必須使用一個Human實例作為第一個參數來調用啊。那我們來試試
 

In [10]: Human.get_weight(Human(45))Out[10]: 45

果然成功了,但是一般情況下我們習慣這么使用。
 

In [11]: person = Human(45) In [12]: person.get_weight()Out[12]: 45

這兩種方式的結果一模一樣。我們看下官方文檔是怎么解釋這種現象的。
 
When an instance attribute is referenced that isn't a data attribute, its class is searched.
If the name denotes a valid class attribute that is a function object, a method object is
created by packing (pointers to) the instance object and the function object just found together
in an abstract object: this is the method object. When the method object is called with an
argument list, a new argument list is constructed from the instance object and the argument list,
and the function object is called with this new argument list.

原來我們常用的調用方法(person.get_weight())是把調用的實例隱藏的作為一個參數self傳遞過去了, self 只是一個普通的參數名稱,不是關鍵字。
 

In [13]: person.get_weightOut[13]: <bound method Human.get_weight of <__main__.Human object at 0x8e13bec>> In [14]: personOut[14]: <__main__.Human at 0x8e13bec>

我們看到get_weight被綁定在了 person 這個實例對象上。
總結下

        instance method 就是實例對象與函數的結合。     使用類調用,第一個參數明確的傳遞過去一個實例。     使用實例調用,調用的實例被作為第一個參數被隱含的傳遞過去。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 兴海县| 沙湾县| 英吉沙县| 洱源县| 永川市| 屏南县| 西畴县| 辽阳市| 威海市| 时尚| 尉氏县| 抚宁县| 稻城县| 鸡西市| 巴林右旗| 荔波县| 建始县| 永顺县| 汶上县| 长宁区| 黑水县| 迁西县| 张家川| 德钦县| 铁力市| 永顺县| 承德县| 清流县| 绥中县| 内黄县| 镇安县| 四川省| 同德县| 天门市| 昭通市| 大关县| 介休市| 丹寨县| 墨竹工卡县| 峡江县| 镇康县|