http://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance

532down voteaccepted

+50

In Python, there is a difference between functions and bound methods.

>>> def foo():
... print "foo"
...
>>> class A:
... def bar( self ):
... print "bar"
...
>>> a = A()
>>> foo
<function foo at 0x00A98D70>
>>> a.bar
<bound method A.bar of <__main__.A instance at 0x00A9BC88>>
>>>

Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.

Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:

>>> def fooFighters( self ):
... print "fooFighters"
...
>>> A.fooFighters = fooFighters
>>> a2 = A()
>>> a2.fooFighters
<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>
>>> a2.fooFighters()
fooFighters

Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):

>>> a.fooFighters()
fooFighters

The problem comes when you want to attach a method to a single instance:

>>> def barFighters( self ):
... print "barFighters"
...
>>> a.barFighters = barFighters
>>> a.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: barFighters() takes exactly 1 argument (0 given)

The function is not automatically bound when it's attached directly to an instance:

>>> a.barFighters
<function barFighters at 0x00A98EF0>

To bind it, we can use the MethodType function in the types module:

>>> import types
>>> a.barFighters = types.MethodType( barFighters, a )
>>> a.barFighters
<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>
>>> a.barFighters()
barFighters

This time other instances of the class have not been affected:

>>> a2.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'barFighters'

types.MethodType的更多相关文章

  1. python中函数和方法区别,以及如何给python类动态绑定方法和属性(涉及types.MethodType()和__slots__)

    网上有很多同义但不同方式的说法,下面的这个说法比较让你容易理解和接受 与类和实例无绑定关系的function都属于函数(function): 与类和实例有绑定关系的function都属于方法(meth ...

  2. python 装饰器(八):装饰器基础(四)types.MethodType的作用

    1 types.MethodType的作用—添加实例方法 import types class cla(object): def __init__(self, name, age): self.nam ...

  3. 运行过程中给类添加方法 types.MethodType

    class Person(object): def __init__(self,name = None,age = None): self.name = name#类中拥有的属性 self.age = ...

  4. python的types模块

    python的types模块 1.types是什么: types模块中包含python中各种常见的数据类型,如IntType(整型),FloatType(浮点型)等等. >>> im ...

  5. 使用types库修改函数

    import types class ppp: pass p = ppp()#p为ppp类实例对象 def run(self): print("run函数") r = types. ...

  6. Python_issubclass&isinstance方法和types&inspect内置模块

    issubclass&isinstance issubclass 用于判断一个类是否是一个已知类或是该已知类的子类.注意,该方法只能判断类不能判断实例化对象. class A: pass cl ...

  7. python黑魔法 -- 内置方法使用

    很多pythonic的代码都会用到内置方法,根据自己的经验,罗列一下自己知道的内置方法. __getitem__ __setitem__ __delitem__ 这三个方法是字典类的内置方法,分别对应 ...

  8. 【python】类(资料+疑惑)

    1.http://python-china.org/t/77 有关method binding的理解 2.[Python] dir() 与 __dict__,__slots__ 的区别 3.Descr ...

  9. Python2.6-原理之类和oop(下)

    来自<python学习手册第四版>第六部分 五.运算符重载(29章) 这部分深入介绍更多的细节并看一些常用的重载方法,虽然不会展示每种可用的运算符重载方法,但是这里给出的代码也足够覆盖py ...

随机推荐

  1. .net framework4与其client profile版本的区别

    简而言之,client profile版本是完整版本的一个子集.包含大多数最常用的功能并减小了体积,以便更容易的安装和发布,同时还有微软所声称的一些好处,比如因为减少了某些库,所以使其更加安全等等. ...

  2. ImportError: cannot import name 'NUMPY_MKL'

    >>> import scipy Traceback (most recent call last): File "<stdin>", line 1, ...

  3. python之lxml(xpath)

    bs4确实没这个好用,bs4的树太复杂 lxml很好 定位非常好 详细解说在注释里面有了 #!/usr/bin/python3.4 # -*- coding: utf-8 -*- from lxml ...

  4. python有序查找算法:二分法

    二分法是一种快速查找的方法,时间复杂度低,逻辑简单易懂,总的来说就是不断的除以2除以2... 例如需要查找有序数组arr里面的某个关键字key的位置,那么首先确认arr的中位数或者中点center,下 ...

  5. 电脑设置固定ip

  6. Struts2 - 常用的constant总结

    见注释 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC &quo ...

  7. 战胜忧虑<2>——忙碌可以消除忧虑

    忙碌可以消除忧虑 当你的脑筋空出来时,也会有东西进去补充,是什么呢?通常都是你的感觉.为什么?因为忧虑.恐惧.憎恨.嫉妒.和羡慕等等情绪,都是由我们的思想所控制的,这种情绪都非常猛烈.会把我们思想中所 ...

  8. python学习-day02

    ---恢复内容开始--- 一.pycharm安装 1.1破解方式http://www.cnblogs.com/evlon/p/4934705.html 1.2.头部配置: 二.运算符 2.1.比较运算 ...

  9. poj1160 post office

    题目大意:有n个乡村,现在要建立m个邮局,邮局只能建在乡村里.现在要使每个乡村到离它最近的邮局距离的总和尽量小,求这个最小距离和. n<300,p<30,乡村的位置不超过10000. 分析 ...

  10. u-boot启动流程分析(1)_平台相关部分

    转自:http://www.wowotech.net/u-boot/boot_flow_1.html 1. 前言 本文将结合u-boot的“board—>machine—>arch—> ...