参考: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. 运行UART的程序

    1 捎程序的时候,注意,捎入的是norflash,此时的按钮应该在norFlash.2 当捎入成功的时候,开始运行程序时,应该把按钮按回nandflash,因为程序的启动就是在nandflash,他把 ...

  2. poj1228稳定凸包

    就是给一系列点,看这是不是一个稳定凸包 稳定凸包是指一个凸包不能通过加点来使它扩大面积,也就是说每条边最少有三个点 判断的地方写错了,写了两边循环,其实数组s已经排好了序,直接每三个判断就好了 #in ...

  3. Tomcat中session共享问题的简单解决办法

    tomcat-redis-session-manager 使用redis配置tomcat共享session 结构图: 分析: 分布式web server集群部署后需要实现session共享,针对 to ...

  4. 22.线程池之ScheduledThreadPoolExecutor

    1. ScheduledThreadPoolExecutor简介 ScheduledThreadPoolExecutor可以用来在给定延时后执行异步任务或者周期性执行任务,相对于任务调度的Timer来 ...

  5. pyhon SyntaxError: Non-ASCII character '\xe8' in file xxx on line xx, but no encoding

    import math if __name__ == '__main__':    name1 = raw_input("请输入您的编号:")    print name1 完整的 ...

  6. asp.net服务器上无法发送邮件的问题

    前几天为开发的网站做了个发送邮件的功能,但是部署到服务器上无法发送邮件,提示由于目标机器积极拒绝,无法连接.在网上找到了一个解决办法 如果安装了McAfee杀毒软件(按照“手工安装方法”安装),首先需 ...

  7. Java 连接操作 Redis 出现错误

    Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: java.n ...

  8. 一款连接SqlServer的数据库工具

    由于自己使用的电脑系统是xp,而服务器上的数据库是SqlServer2012,于是用SqlServer2005管理端操作2012,总是不成功.在网上也百度谷歌了很久,也没有解决,也发了很多问没有找到解 ...

  9. log4cpp安装

    body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...

  10. nodejs之log4js日志记录模块简单配置使用

    在我的一个node express项目中,使用了log4js来生成日志并且保存到文件里,生成的文件如下: 文件名字叫:access.log 如果在配置log4js的时候允许了同时存在多个备份log文件 ...