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. noip2014普及组 比例简化

    题目描述 在社交媒体上,经常会看到针对某一个观点同意与否的民意调查以及结果.例如,对某一观点表示支持的有1498 人,反对的有 902人,那么赞同与反对的比例可以简单的记为1498:902. 不过,如 ...

  2. Oboe 提升web 用户体验以及性能

    Oboe  地址:http://oboejs.com/ 1.安装  bower bower  install oboe 2.使用,ajax 模式 oboe('/myapp/things.json') ...

  3. 【转】深入PHP FTP类的详解

    FTP是一种文件传输协议,它支持两种模式,一种方式叫做Standard (也就是Active,主动方式),一种是 Passive (也就是PASV,被动方式). Standard模式 FTP 的客户端 ...

  4. Ajax编程中,经常要能动态的改变界面元素的样式

    在Ajax编程中,经常要能动态的改变界面元素的样式,可以通过对象的style属性来改变,比如要改变背景色为红色,可以这样写:element.style.backgroundColor=”#ff0000 ...

  5. hadoop-2.7.0

    65 cd /home/guyumei/下载/ 66 ll 67 cd .. 68 ll 69 cd .. 70 ll 71 cd guyumei/ 72 ll 73 cd hadoop-2.7.0/ ...

  6. ExtJs学习笔记之学习小结LoginDemo

    ExtJs学习小结LoginDemo 1.示例:(登录界面) <!DOCTYPE html> <html> <head> <meta charset=&quo ...

  7. ScrumMaster需要了解的7件事

    当一个组织开始使用Scrum时,被选为担任Scrumaster角色的人通常来自于那些有管理背景的人.组织期望那些管理人员,所谓的“大师”,能够交付Scrum项目因为她有管理的专门知识——并且可以同时管 ...

  8. asp.net获取当前网址url的各种属性(文件名、参数、域名 等)的代码

    用 asp.net获取当前网页地址的一些信息. 设当前页完整地址是:http://www.jb51.net/aaa/bbb.aspx?id=5&name=kelli "http:// ...

  9. 斐波那契(Fibonacci)数列的几种计算机解法

    题目:斐波那契数列,又称黄金分割数列(F(n+1)/F(n)的极限是1:1.618,即黄金分割率),指的是这样一个数列:0.1.1.2.3.5.8.13.21.34.…….在数学上,斐波纳契数列以如下 ...

  10. MSCRM Plugin Debug

    MS CRM 2011的自定义和开发(11)——插件(plugin)开发(四) 上面几篇文章介绍了Microsoft Dynamics CRM 2011中如何进行插件开发,本文将介绍插件的调试. 调试 ...