ficapy
8/22/2015 - 2:30 AM

adding a method to an exists object&Monkey Path

adding a method to an exists object&Monkey Path

class A(object):
    pass

a = A()

# 给类添加方法
def baz(self):
    print('baz')
A.baz = baz
# ==========或者
setattr(A,'baz',baz)
a.baz()

# Monkey Path就是简单的替换啦
def monkey_path_baz(self):
    print('simple replace')
A.baz = monkey_path_baz
a.baz()

# ===========================动态给实例化对象添加方法
def foo(self):
    print('foo')
    
import types
a.foo = types.MethodType(foo,a)
a.foo()
# 或者=============================(就是将对象本身当做第一个参数传递给函数)

from functools import partial

def bar(self):
    print('bar')
a.bar = partial(bar,a)
a.bar()

# 或者=============================(同上)
def qux(self):
    print('qux')
a.qux = lambda :qux(a)
a.qux()