2012-07-19 28 views
2

是否可以爲方法編寫包裝函數?是否可以將字符串方法作爲函數來處理?

>>> lowtide = [ 'oh', 'i', 'do', 'like', 'to', 'be', 'beside', 'the', 'seaside' ] 

>>> [ x.capitalize() for x in lowtide ] 
['Oh', 'I', 'Do', 'Like', 'To', 'Be', 'Beside', 'The', 'Seaside'] 

>>> list(map(lambda x: x.capitalize(), lowtide)) 
['Oh', 'I', 'Do', 'Like', 'To', 'Be', 'Beside', 'The', 'Seaside'] 


>>> def mef(m): 
...  def _mef(m,x): 
...   return x.m() 
...  return partial(_mef, m) 
... 
>>> list(map(mef(capitalize), lowtide)) 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'capitalize' is not defined 
+1

你的'mef'函數可以通過用'getattr(x,m)'替換'x.m'來工作。 – 2012-07-19 22:49:07

回答

5

儘管可以使用str.capitalizeunicode.capitalize,這些都可以,如果你認爲某些類型的失敗......最安全的方法是隻使用:

from operator import methodcaller 
capitalize = methodcaller('capitalize') 

保證了正確的方法是使用對象,並且還允許鴨子打字成功完成。從後從我這裏谷歌論壇

摘錄/ comp.lang.python的2010年8月23日

使用methodcaller讓你「保留」 Python的鴨打字的 以及任何纏身的過方法在子類中。在你的榜樣,這 可能是矯枉過正因爲你只用一類處理

另一個(曲)例如:

class mystr(str): 
    def lower(self): 
     return self.upper() 

>>> s = mystr('abc') 
>>> s.lower() 
'ABC' 

>>> lower = methodcaller('lower') 
>>> lower(s) 
'ABC' 

>>> str.lower(s) 
'abc' 

^^^最有可能不正確

它還增加了更多的靈活性(可以用 functools.partial公認地模仿):

split_tab = methodcaller('split', '\t') 
split_comma = methodcaller('split', ',') 
+0

+1我從來不知道methodcaller。很有意思 – beoliver 2012-07-19 23:03:42

8

你可以簡單地做

list(map(str.capitalize, lowtide)) 

在Python 3.x中,str.capitalize()走的是單一參數self的功能。

在Python 2.x中,str.capitalize()是一個「未綁定的方法」,但其行爲類似於採用單個參數的函數。

+0

+1當事情很簡單時,它總是很好的 – beoliver 2012-07-19 23:03:18

1

下面介紹如何重寫mef函數以使其正常工作。在這裏使用str.capitalize的好處是,它會爲Unicode字符串的工作以及關於Python 2.x的:

def mef(m): 
    def _mef(x): 
     return getattr(x, m)() 
    return _mef 

list(map(mef('capitalize'), lowtide)) 

注意,這在本質上是一樣的東西用lambda x: x.capitalize()

+0

+1因爲這正是我想要做的 – beoliver 2012-07-19 23:04:16

相關問題