親愛的蟒蛇專家3人,python2 VS python3函數方法結合
與python2,一個可以做到以下幾點(我知道這是一個有點毛茸茸的,但在這裏,這不是問題的關鍵:P):
class A(object):
def method(self, other):
print self, other
class B(object): pass
B.method = types.MethodType(A().method, None, B)
B.method() # print both A and B instances
與python3,沒有更多的未綁定方法,只有函數。如果我想相同的行爲,這聽起來像我所介紹的自定義描述符,如:
class UnboundMethod:
"""unbound method wrapper necessary for python3 where we can't turn
arbitrary object into a method (no more unbound method and only function
are turned automatically to method when accessed through an instance)
"""
def __init__(self, callable):
self.callable = callable
def __get__(self, instance, objtype):
if instance is None:
return self.callable
return types.MethodType(self.callable, instance)
所以我可以做:
B.method = UnboundMethodType(A().method)
B.method() # print both A and B instances
是否有任何其他方式做到這一點無需編寫這樣的描述符?
TIA
快速,脫離主題的評論:無需派生自Py3中的對象。它總是隱含的。檢查,只是'print(anyobject .__ mro __)'(=方法解析順序) – cfi
我相信這是一個重複的[http://stackoverflow.com/questions/10729909/convert-builtin-function-type-to-method型合蟒-3]。然而,這個問題可能更容易找到。另外它更清晰(至少對我來說),所以我會投票保留這個... – cfi
@cfi,關於對象繼承的真,修正了UnboundMethod代碼示例。你也是對的,這是一個類似的問題,因爲綁定編譯/內置函數(它沒有滿足答案btw) – sthenault