Warm tip: This article is reproduced from serverfault.com, please click

python 3.x-是否可以参数化点表示法调用的方法?

(python 3.x - Is it possible to parametrize a method being called by dot notation?)

发布于 2020-11-28 05:15:46

就像标题所说的那样,我正在尝试找出是否可以参数化通过点表示法调用的方法。

def funk(x,a_class_method):
    return [i.a_class_method() for i in x]
    
a_class_method = upper
funk(x,a_class_method)

输入

x = ['hi', 'my', 'name', 'is', 'frank']

期望的输出

['HI', 'MY', 'NAME', 'IS', 'FRANK']

如写的那样

NameError:名称“ upper”未定义

Questioner
will.cass.wrig
Viewed
0
HTNW 2020-11-28 13:42:09

通常,传递函数并不是思考/做事情的好方法。只需传递函数

def funk(x, f):
    return [f(i) for i in x]

funk(['hi', 'my', 'name', 'is', 'frank'], str.upper) # pass the method itself
# str.upper(x) is the same as x.upper() for any str x
# or write
funk(['hi', 'my', 'name', 'is', 'frank'], lambda x: x.upper()) # pass a function that calls the method
# (lambda x: x.upper())(y) is the same as y.upper()
# you could also write the following (but why would you?)
def oneOffFunction(x):
    return x.upper()
funk(['hi', 'my', 'name', 'is', 'frank'], oneOffFunction) # pass another function that calls the method

使用第一种形式要求你知道要在其上调用方法的对象的类型。使用第二和第三种方法,你可以纯粹通过名称来调用该方法,而与类型无关。你很少会想要/需要这种getattr方式。

请注意,这funk(xs, f)等效于list(map(f, xs))