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

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'

More information can be found by reading about descriptors and metaclass programming.

python动态给对象或者类添加方法的更多相关文章

  1. python动态获取对象的属性和方法 (转载)

    首先通过一个例子来看一下本文中可能用到的对象和相关概念. #coding:utf-8 import sys def foo():pass class Cat(object): def __init__ ...

  2. python动态获取对象的属性和方法 (转)

    转自未知,纯个人笔记使用 首先通过一个例子来看一下本文中可能用到的对象和相关概念. #coding:utf-8 import sys def foo():pass class Cat(object): ...

  3. python动态获取对象的属性和方法

    http://blog.csdn.net/kenkywu/article/details/6822220首先通过一个例子来看一下本文中可能用到的对象和相关概念.01     #coding: UTF- ...

  4. python 动态调用模块、类、方法(django项目)

    需求:近一段时间基于django框架,开发各业务层监控代码,每个业务的监控逻辑不同,因此需要开发监控子模块,动态的导入调用. 项目名称:demo_django App:common_base.moni ...

  5. C#动态创建和动态使用程序集、类、方法、字段等

    C#动态创建和动态使用程序集.类.方法.字段等 分类:技术交流 (3204)  (3)   首先需要知道动态创建这些类型是使用的一些什么技术呢?其实只要相关动态加载程序集呀,类呀,都是使用反射,那么动 ...

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

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

  7. [19/10/14-星期一] Python中的对象和类

    一.面向对象 ## 什么是对象? - 对象是内存中专门用来存储数据的一块区域. - 对象中可以存放各种数据(比如:数字.布尔值.代码) - 对象由三部分组成: 1.对象的标识(id) 2.对象的类型( ...

  8. C#中的扩展方法(向已有类添加方法,但无需创建新的派生类型)

    C#中的扩展方法 扩展方法使你能够向现有类型"添加"方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样 ...

  9. 调用其他python脚本文件里面的类和方法

    问题描述: 自己编写了若干个Python脚本. 在testC.py里面需要调用testA.py和testB.py里面的若干类和方法.要怎么办? 需要都打包.安装,再去调用吗? 其实不必那么麻烦. 这里 ...

随机推荐

  1. css tips —— 在css中完成国际化

    前提 在日常处理国际化的时候,通常是将key通过类似intl.xx(key)转换为对应环境的文案,可是如果需要在css中加入对应逻辑应该怎么做呢(比如在after的伪元素中显示不同的文案),毕竟在cs ...

  2. JS正则表达式入门,看这篇就够了

    前言 在正文开始前,先说说正则表达式是什么,为什么要用正则表达式?正则表达式在我个人看来就是一个浏览器可以识别的规则,有了这个规则,浏览器就可以帮我们判断某些字符是否符合我们的要求.但是,我们为什么要 ...

  3. 19.并发容器之BlockingQueue

    1. BlockingQueue简介 在实际编程中,会经常使用到JDK中Collection集合框架中的各种容器类如实现List,Map,Queue接口的容器类,但是这些容器类基本上不是线程安全的,除 ...

  4. DXVA2解码数据用texture纹理渲染

    FFmpeg DXVA2解码得到的数据使用surface来承载的,surface限制很多,如果能用纹理来渲染的话,那我们就可以充分开发D3D,比如可以用坐标变换来实现电子放大的功能,还可以用坐标变换来 ...

  5. IOS-CocoaPods制作篇

    作者:wangzz 原文地址:http://blog.csdn.net/wzzvictory/article/details/20067595 转载请注明出处 如果觉得文章对你有所帮助,请通过留言或关 ...

  6. 使用Eclipse EE(汉化版) 创建一个JavaWeb工程

    第一步:打开eclipse ee,单击“文件”-->单击“新建”-->单击“动态Web项目”. 若没找到“动态Web项目”,单击“其他” -->在弹出的窗口中打开“Web”下拉菜单 ...

  7. gridview 后台增加列

    BoundField field1 = null; field1 = new BoundField();  //实例化 field1.HeaderText = "序号";field ...

  8. PHP工作笔记:遍历文件夹返回文件数组

    直接输入文件夹的路径,调用函数即可返回文件夹里面的文件数组,不返回文件夹 <?php function scanfiles($folder){ $folder = $folder."* ...

  9. 说说C++多重继承

    尽管大多数应用程序都使用单个基类的公用继承,但有些时候单继承是不够用的,因为可能无法为问题域建模或对模型带来不必要的复杂性.在这种情况下,多重继承可以更直接地为应用程序建模. 一.基本概念 多重继承是 ...

  10. APUE学习笔记——10信号——信号接口函数 signal 和 sigaction

    signal函数     signal函数是早起Unix系统的信号接口,早期系统中提供不可靠的信号机制.在后来的分支中,部分系统使用原来的不可靠机制定义signal函数,如 Solaris 10 .而 ...