python类的成员函数_注入一个python类成员函数
你在這里要做的是Child2.foo用self不是a的方法調用未綁定的方法Child2。
這是非法的,Python 2將檢測到并提出一個TypeError解釋錯誤的地方:TypeError: unbound method foo() must be called with Child1 instance as first argument (got Child2 instance instead)
在Python 3中,沒有未綁定的方法對象; 未綁定的方法只是普通的舊函數。因此,他們無法檢查您是否正在嘗試做任何違法行為。然后,因為你實際上并沒有使用方法內部的事實,self所以你可以逃脫它。Child2foo
但你不能注入實際使用的方法Child2的-ness Child2這種方式; 他們最終會提出一個TypeError或者說AttributeError錯誤的方法。它只適用于首先沒有理由成為方法的方法。
如果你真的想在Python 2中使用這種行為,你可以通過從未綁定方法中提取函數來獲得它:self.d['foo'] = Child1.foo.__func__
(如果你想使用更老的2.x,請使用im_func而不是__func__那里。)
現在,它根本不是一種方法 - 如果你試圖將它實際上與self描述符協議綁定或者通過構建一個方法MethodType,你就會得到相同的舊方法TypeError。但它是一個函數,你可以用你想要的任何參數作為函數來調用它。而且,因為你的函數對self那個要求它的參數沒有任何作用Child2,所以它會起作用。
雖然我們在這里,你幾乎肯定想Parent在這里成為一個新式的課程。您可能希望在Python 2和Python 3中使用相同的代碼,而不是在兩者中使用相同行為的不同代碼。所以:class Parent(object): # makes it a new-style class in 2.x as well as 3.x
def foo(self):
print("foo of class Parent: instance " + self.__class__.__name__)
def __init__(self):
self.d = {"foo": self.__class__.foo}
def bar(self):
self.d['foo'](self)
# Gets __func__ if it's an unbound method (2.x), leaves it alone if not (3.x)
self.d['foo'] = getattr(Child1.foo, '__func__', Child1.foo)
self.d['foo'](self)
class Child1(Parent):
def foo(self):
print("foo of class Child1: instance " + self.__class__.__name__)
class Child2(Parent):
pass
Child2().bar()
總結
以上是生活随笔為你收集整理的python类的成员函数_注入一个python类成员函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python实现文本编辑器_Python
- 下一篇: python json.load_pyt