2017-06-08 36 views
2

我在Python 2.7以下類:如何調用未法在子類的對象在Python

class Parent(): 
    def some_method(self): 
     do_something() 

class Child(Parent): 
    def some_method(self): 
     do_something_different() 

假設我有一堆我要上運行some_method對象。我執行以下行(前兩個是這個例子的目的):

c = Child() 
m = Parent.some_method 

m(c) # do_something() gets called 

有一些結構使得在最後一行do_something_different()被稱爲替代,而無需使用任何有關Child(我可能有很多這樣的類繼承Parent)?

回答

4

比使用未綁定方法對象相反,使用operator.methodcaller

import operator 

m = operator.methodcaller('some_method') 

m(c) 

這將查找對象的實際some_method方法,並調用它。這是更昂貴的,但額外的時間都花在做你需要的東西。

+0

這非常接近我所需要的!有沒有辦法做到這一點,如果我只能訪問未綁定的方法,而不是它的名字? – Nibor

+0

找到它,只需調用'm .__ name__' – Nibor

+0

@Nibor:請注意'__name__'可能與屬性名稱不匹配。 'Foo.bar'可能有'egg'的'__name__'。 – user2357112

相關問題