2011-09-21 55 views
9

我想添加一個方法到'list'類的單個實例。例如:在Python中添加一個列表實例的方法

a = [1,2] 
a.first = lambda self: return self[0] 

我知道這是行不通的,但我想像那樣的作品。我知道這不是一個好習慣,我知道我應該做一個全新的課程,但我認爲這在Python中是可行的,並且還沒有想出如何。

我所知道的: Dynamically add member function to an instance of a class in PythonDynamically binding Python methods to an instance correctly binds the method names, but not the method

但沒有那些工作與本地列表。

謝謝!

+1

注意:不要對lambda表達式使用'return'。 –

+1

你想做'a.first = lambda:a [0]'或'a.first = types.MethodType(lambda self:self [0],a)'。如果您將函數添加到像這樣的對象,Python將不會自動將其綁定到對象。 –

+0

查看http://stackoverflow.com/questions/6738987/extension-method-for-python-built-in-types – OlivierBlanvillain

回答

12

由於無法將方法添加到C中定義的類型中,因此無法使用本機列表。您需要從list派生方法並將該方法添加到該類中。

+0

哦,你好,這真是太棒了......謝謝:) – rgenito