是否可以将字符串方法视为函数?

beo*_*ver 2 python methods function

是否可以为方法编写包装函数?

>>> 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
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 8

你可以干脆做

list(map(str.capitalize, lowtide))
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中,str.capitalize()是一个采用单个参数的函数self.

在Python 2.x中,str.capitalize()是一个"未绑定的方法",但行为类似于采用单个参数的函数.


Jon*_*nts 5

虽然你可以使用str.capitalizeunicode.capitalize,如果你假设某种类型,这些可能会失败...最安全的方法是使用:

from operator import methodcaller
capitalize = methodcaller('capitalize')
Run Code Online (Sandbox Code Playgroud)

这保证了对象使用了正确的方法,并且还允许成功完成duck typing.

摘自我的帖子到Google Groups/comp.lang.python 2010年8月23日

使用methodcaller可以让你"保留"Python的duck-typing以及子类中任何过度使用的方法.在你的例子中,这可能是过度的,因为你只处理一个类

另一个(复杂的)例子:

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'
Run Code Online (Sandbox Code Playgroud)

^^^最有可能是不正确的

它还增加了一点灵活性(可以用functools.partial模仿):

split_tab = methodcaller('split', '\t')
split_comma = methodcaller('split', ',')
Run Code Online (Sandbox Code Playgroud)