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. Openjudge计算概论-单词翻转

    /*===================================== 单词翻转 总时间限制: 1000ms 内存限制: 65536kB 描述 输入一个句子(一行),将句子中的每一个单词翻转后 ...

  2. js防止回车(enter)键提交表单及javascript中event.keycode

      如何防止回车(enter)键提交表单,其实很简单,就一句话.onkeydown="if(event.keyCode==13)return false;"把这句写在from标签里 ...

  3. SQL SERVER 生成建表脚本

    /****** Object: StoredProcedure [dbo].[GET_TableScript_MSSQL] Script Date: 06/15/2012 11:59:00 ***** ...

  4. Hibernate常用配置文件详解

    本文转载自:http://blog.csdn.net/csh624366188/article/details/7578939 初学hibernate的童鞋,刚开应该都有这种感觉,hibernate的 ...

  5. (转帖)BootStrap入门教程 (三)

      上讲回顾:Bootstrap的基础CSS(Base CSS)提供了优雅,一致的多种基础Html页面要素,包括排版,表格,表单,按钮等,能够满足前端工程师的基本要素需求. Bootstrap作为完整 ...

  6. openstack(liberty): devstack中的iniset/iniget函数分析

    这个ini开头的函数在devstack的启动配置中用的非常多,他主要负责.ini文件的配置,这个过程包括对相关ini文件的添加,注释,删除,获取信息,多行信息获取等. 这里主要说的iniset和ini ...

  7. Flex外包团队—开发工具:Flex4.6新特性介绍

    在今年初,Adobe发布了其第一个支持移动应用程序开发的Flex SDK和Flash Builder版本.Flex 4.5引入了一组移动优化的组件和移动优化的应用程序框架,而Flash Builder ...

  8. POWERDESIGNER中显示样式设置

    1.调整表.视图的显示样式. 右键选中的对象,选择format(或ctrl+t),在弹出窗口中选中content,可以设置只显示表名还是把所有列也显示出来. 2.如何显示表中字段的code. tool ...

  9. NOR Flash擦写和原理分析 (二)

    Nor Flash上电后处于数据读取状态(Reading Array Data).此状态可以进行正常的读.这和读取SDRAM/SRAM/ROM一样.(要是不一样的话,芯片上电后如何从NorFlash中 ...

  10. linux系统中实现mongodb3.0.5数据库自动备份

    最近两天,因公司业务需要,要定期备份mongodb数据库中的数据. 查了很多资料后,发现mongodb似乎并没有自带的定时备份功能,于是只好转移目标到linux系统的定时任务上,于是学习并使用了cro ...