就像标题所说的那样,我正在尝试找出是否可以参数化通过点表示法调用的方法。
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”未定义
通常,传递函数名并不是思考/做事情的好方法。只需传递函数:
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))
这太完美了,谢谢!我不知道
str.upper
传递类方法的方式。