参考: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. Cookie和Session的工作原理及比较

    一.Cookie详解 (1)简介 因为HTTP协议是无状态的,即服务器不知道用户上一次做了什么,这严重阻碍了交互式Web应用程序的实现.在典型的网上购物场景中,用户浏览了几个页面,买了一盒饼干和两饮料 ...

  2. vim 正则 捕获

    在正规表达式中使用 \( 和 \) 符号括起正规表达式,即可在后面使用\1 \2等变量来访问捕获的内容. 将捕获内容前后交换,如下: :s/\(\haha\)\(hehe\)/\\/

  3. Java Object类的方法

    1. Java中所有的类都直接或者间接地继承自Object类.当没有显式地声名一个类的父类时,它会隐式地继承Object类. 2. Object类中定义了适合于任何Java对象的方法. String ...

  4. (3) iOS开发之UI处理-UIView篇

    在UIView作为许多子控件的容器的时候,首先我们需要动态的计算出UIView下的所有子控件的高度,并布局排列好,然后我们还要把作为容器的UIView的高度调整到刚好包裹着所有子控件,不会过矮,也不会 ...

  5. 个人知识管理系统Version1.0开发记录(03)

    demo  设 计 一个知识点demo,在数据库和用户界面的互动事件.分三个层次,数据存储,数据方法工具,数据呈现界面.这一次先完成数据存储,按以下逻辑实现.工具:eclipse,oracle数据库, ...

  6. spring boot @ConditionalOnxxx相关注解

    @Conditional(TestCondition.class) 这句代码可以标注在类上面,表示该类下面的所有@Bean都会启用配置,也可以标注在方法上面,只是对该方法启用配置. Spring框架还 ...

  7. (转)让IE6/IE7/IE8浏览器支持CSS3属性

    原文链接 http://blog.csdn.net/h5_queenstyle12/article/details/50437442 一.下载 搜索下载:ie-css3.htc,它是让IE浏览器支持C ...

  8. hdu 6040 Hints of sd0061(stl: nth_element(arr,arr+k,arr+n))

    Hints of sd0061 Time Limit: 5000/2500 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others ...

  9. UML_02_概述

    一.前言 UML(Unified Modeling Language)是一种统一建模语言,为面向对象开发系统的产品进行说明.可视化.和编制文档的一种标准语言 二.分类 UML 的核心是图表,大致可以将 ...

  10. LeetCode OJ:Group Anagrams(同字符字符群)

    Given an array of strings, group anagrams together. For example, given: ["eat", "tea& ...