用实例分析Python中method的参数传递过程


Posted in Python onApril 02, 2015

什么是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_weight
Out[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_weight
Out[13]: <bound method Human.get_weight of <__main__.Human object at 0x8e13bec>>
 
In [14]: person
Out[14]: <__main__.Human at 0x8e13bec>

我们看到get_weight被绑定在了 person 这个实例对象上。
总结下

  1.     instance method 就是实例对象与函数的结合。
  2.     使用类调用,第一个参数明确的传递过去一个实例。
  3.     使用实例调用,调用的实例被作为第一个参数被隐含的传递过去。

classmethod
 

In [1]: class Human(object):
  ...:   weight = 12
  ...:   @classmethod
  ...:   def get_weight(cls):
  ...:     return cls.weight
 
In [2]: Human.get_weight
Out[2]: <bound method type.get_weight of <class '__main__.Human'>>

我们看到get_weight是一个绑定在 Human 这个类上的method。调用下看看
 

In [3]: Human.get_weight()
Out[3]: 12
In [4]: Human().get_weight()
Out[4]: 12

类和类的实例都能调用 get_weight 而且调用结果完全一样。
我们看到 weight 是属于 Human 类的属性,当然也是 Human 的实例的属性。那传递过去的参数 cls 是类还是实例呢?
 

In [1]: class Human(object):
  ...:   weight = 12
  ...:   @classmethod
  ...:   def get_weight(cls):
  ...:     print cls
 
In [2]: Human.get_weight()
<class '__main__.Human'>
 
In [3]: Human().get_weight()
<class '__main__.Human'>

我们看到传递过去的都是 Human 类,不是 Human 的实例,两种方式调用的结果没有任何区别。cls 只是一个普通的函数参数,调用时被隐含的传递过去。
总结起来

  1.     classmethod 是类对象与函数的结合。
  2.     可以使用类和类的实例调用,但是都是将类作为隐含参数传递过去。
  3.     使用类来调用 classmethod 可以避免将类实例化的开销。

staticmethod
 

In [1]: class Human(object):
  ...:   @staticmethod
  ...:   def add(a, b):
  ...:     return a + b
  ...:   def get_weight(self):
  ...:     return self.add(1, 2)
 
In [2]: Human.add
Out[2]: <function __main__.add>
 
In [3]: Human().add
Out[3]: <function __main__.add>
 
In [4]: Human.add(1, 2)
Out[4]: 3
 
In [5]: Human().add(1, 2)
Out[5]: 3

我们看到 add 在无论是类还是实例上都只是一个普通的函数,并没有绑定在任何一个特定的类或者实例上。可以使用类或者类的实例调用,并且没有任何隐含参数的传入。
 

In [6]: Human().add is Human().add
Out[6]: True
 
In [7]: Human().get_weight is Human().get_weight
Out[7]: False

add 在两个实例上也是同一个对象。instancemethod 就不一样了,每次都会创建一个新的 get_weight 对象。
总结下

  1.     当一个函数逻辑上属于一个类又不依赖与类的属性的时候,可以使用 staticmethod。
  2.     使用 staticmethod 可以避免每次使用的时都会创建一个对象的开销。
  3.     staticmethod 可以使用类和类的实例调用。但是不依赖于类和类的实例的状态。
Python 相关文章推荐
简单上手Python中装饰器的使用
Jul 12 Python
python实现爬虫统计学校BBS男女比例之数据处理(三)
Dec 31 Python
Python实现的多线程http压力测试代码
Feb 08 Python
插入排序_Python与PHP的实现版(推荐)
May 11 Python
Python Xml文件添加字节属性的方法
Mar 31 Python
python 判断参数为Nonetype类型或空的实例
Oct 30 Python
python写入文件自动换行问题的方法
Jul 05 Python
Django的models模型的具体使用
Jul 15 Python
pyqt5、qtdesigner安装和环境设置教程
Sep 25 Python
python异步Web框架sanic的实现
Apr 27 Python
Python求区间正整数内所有素数之和的方法实例
Oct 13 Python
python获得命令行输入的参数的两种方式
Nov 02 Python
使用优化器来提升Python程序的执行效率的教程
Apr 02 #Python
使用Python脚本对Linux服务器进行监控的教程
Apr 02 #Python
在Python编程过程中用单元测试法调试代码的介绍
Apr 02 #Python
用Python的Django框架完成视频处理任务的教程
Apr 02 #Python
用map函数来完成Python并行任务的简单示例
Apr 02 #Python
对于Python异常处理慎用“except:pass”建议
Apr 02 #Python
Python的设计模式编程入门指南
Apr 02 #Python
You might like
yii框架表单模型使用及以数组形式提交表单数据示例
2014/04/30 PHP
基于ThinkPHP+uploadify+upload+PHPExcel 无刷新导入数据
2015/09/23 PHP
两种php去除二维数组的重复项方法
2015/11/04 PHP
Linux安装配置php环境的方法
2016/01/14 PHP
JS去除字符串的空格增强版(可以去除中间的空格)
2009/08/26 Javascript
firefox下jQuery UI Autocomplete 1.8.*中文输入修正方法
2012/09/19 Javascript
JQuery切换显示的效果实例代码
2013/02/27 Javascript
js实现点小图看大图效果的思路及示例代码
2013/10/28 Javascript
利用javascript打开模态对话框(示例代码)
2014/01/11 Javascript
jQuery将所有被选中的checkbox某个属性值连接成字符串的方法
2015/01/24 Javascript
js实现左侧网页tab滑动门效果代码
2015/09/06 Javascript
jQuery 1.9.1源码分析系列(十五)动画处理之缓动动画核心Tween
2015/12/03 Javascript
Bootstrap学习笔记之js组件(4)
2016/06/12 Javascript
JS清除字符串中重复值的实现方法
2016/08/03 Javascript
浅谈JavaScript的闭包函数
2016/12/08 Javascript
基于JS递归函数细化认识及实用实例(推荐)
2017/08/07 Javascript
jQuery DOM节点的遍历方法小结
2017/08/15 jQuery
对Vue table 动态表格td可编辑的方法详解
2018/08/28 Javascript
JavaScript模板引擎原理与用法详解
2018/12/24 Javascript
JS实现选项卡效果的代码实例
2019/05/20 Javascript
微信小程序发布新版本时自动提示用户更新的方法
2019/06/07 Javascript
Vue.js暴露方法给WebView的使用操作
2020/09/07 Javascript
[01:10]为家乡而战!完美世界城市挑战赛全国总决赛花絮
2019/07/25 DOTA
[33:19]完美世界DOTA2联赛PWL S2 PXG vs InkIce 第一场 11.26
2020/11/30 DOTA
Python网页解析利器BeautifulSoup安装使用介绍
2015/03/17 Python
Python中使用第三方库xlrd来写入Excel文件示例
2015/04/05 Python
Python UnboundLocalError和NameError错误根源案例解析
2018/10/31 Python
python 判断矩阵中每行非零个数的方法
2019/01/26 Python
美国渔具店:FishUSA
2019/08/07 全球购物
有机婴儿毛毯和衣服:Monica + Andy
2020/03/01 全球购物
班组长竞聘书
2014/03/31 职场文书
2014年民政局关于保密工作整改措施
2014/09/19 职场文书
三方股份合作协议书
2014/10/13 职场文书
质量整改通知单
2015/04/21 职场文书
mybatis-plus模糊查询指定字段
2022/04/28 Java/Android
Redis实现订单过期删除的方法步骤
2022/06/05 Redis