Created
August 22, 2015 02:30
-
-
Save ficapy/0c240984f2a470468161 to your computer and use it in GitHub Desktop.
adding a method to an exists object&Monkey Path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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