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. wikioi 1204 寻找子串位置

    /*======================================================================== 1204 寻找子串位置 题目描述 Descript ...

  2. webpack 多entry 配置

    // webpack 多entry 配置var path = require('path'); module.exports = { entry: { entry2: './entry.js', de ...

  3. es6新特性

    变量-------------------------- let, const:必须直接给一个变量赋值.注意,对象的属性或数组成员还是可以改变的. const MY_OBJECT = {some: 1 ...

  4. DebugDiag收集Dump的使用说明

    DebugDiag简介 Debug Diagnostic Tool (DebugDiag)是微软提供的工具,可以用来追踪windows平台下的程序崩溃,卡死,内存泄漏等一些疑难问题的原因,按照问题类别 ...

  5. HTML <div> 和 <span>

    可以通过 <div> 和 <span> 将 HTML 元素组合起来. HTML 块元素 大多数 HTML 元素被定义为块级元素或内联元素. 编者注:“块级元素”译为 block ...

  6. (转)jQuery禁止右键菜单,全选

    本文转载自:http://www.cnblogs.com/lucker/archive/2012/09/21/2696464.html $("body").bind("c ...

  7. PHP导出数据到CSV文件

    后台往往需要导出各种数据到 Excel文档中.通常我们是导出 .csv文件格式,PHP导出函数参考代码如下: /** * 导出数据到CSV文件 * * @param array $data 二维数组( ...

  8. 【springBoot】springBoot返回json的一个问题

    首先看下面的代码 @Controller @RequestMapping("/users") public class UserController { @RequestMappi ...

  9. RDA 编译器的搭建

    apt-get install subversion apt-get install make atp-get install gcc sudo vim /etc/profile export PAT ...

  10. ADF_Starting系列1_JDeveloper IDE开发环境简介

    2013-05-01 Created By BaoXinjian