Skip to content

Instantly share code, notes, and snippets.

@ficapy
Created August 22, 2015 02:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ficapy/0c240984f2a470468161 to your computer and use it in GitHub Desktop.
Save ficapy/0c240984f2a470468161 to your computer and use it in GitHub Desktop.
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment