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

标签 python function methods

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

>>> 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

最佳答案

你可以简单地做

list(map(str.capitalize, lowtide))

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

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

关于python - 是否可以将字符串方法视为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11570426/

相关文章:

c# - 如何从函数中检索输入

python - 在函数装饰器中调用 Python 实例方法

java - 掷骰子的方法

没有 "log.xxxx"的 Scala 调用记录方法

python - 在 Python 2.5 中将 Google App Engine blobstore 作为文件写入的正确方法是什么

python - 列出所有可能包含 n 个字母的单词

python - 我怎样才能在Python中实现这个方程?

python - 添加到 Python 2.7 中的列表

python - 使用 XMLRPC 在 Python 中进行动态函数调用

R 在函数内使用临时选项设置