Python 避免不必要地使用lambda调用对象方法

Python 避免不必要地使用lambda调用对象方法,python,Python,考虑以下代码,该代码仅对列表的每个成员调用一个方法: class Demo: def make_change(self): pass foo = [Demo(), Demo(), Demo()] map(lambda x: x.make_change(), foo) 有没有办法不用冗长的lambda语法来实现这一点?例如,在Scala中,类似于map(u.make\u change(),foo)。Python是否有一个等价物?仅仅为了副作用而使用map并不是很适合Py

考虑以下代码,该代码仅对列表的每个成员调用一个方法:

class Demo:
    def make_change(self):
        pass

foo = [Demo(), Demo(), Demo()]
map(lambda x: x.make_change(), foo)

有没有办法不用冗长的
lambda
语法来实现这一点?例如,在Scala中,类似于
map(u.make\u change(),foo)
。Python是否有一个等价物?

仅仅为了副作用而使用map并不是很适合Python的

operator.methodcaller('make_change')
那为什么不呢

for item in foo:
    item.make_change()
这将比使用map运行得更快

如果你坚持的话,你可以把它放在一行上,但我不会

for item in foo:item.make_change()

仅仅为了副作用而使用map不是一种很好的方法

那为什么不呢

for item in foo:
    item.make_change()
这将比使用map运行得更快

如果你坚持的话,你可以把它放在一行上,但我不会

for item in foo:item.make_change()

我和gnibbler在pythonicity一起。除此之外,这也是可能的:

map(Demo.make_change, foo)
但它也有问题:

class Demo(object):
    def __init__(self):
        self.x = 1
        self.y = 2
    def make_change(self):
        self.x = 5

class SubDemo(Demo):
    def make_change(self):
        self.y = 7

d = Demo()
s = SubDemo()
map(Demo.make_change, [d, s])

assert d.x == 5 and s.y == 7 # oops!

我和gnibbler在pythonicity一起。除此之外,这也是可能的:

map(Demo.make_change, foo)
但它也有问题:

class Demo(object):
    def __init__(self):
        self.x = 1
        self.y = 2
    def make_change(self):
        self.x = 5

class SubDemo(Demo):
    def make_change(self):
        self.y = 7

d = Demo()
s = SubDemo()
map(Demo.make_change, [d, s])

assert d.x == 5 and s.y == 7 # oops!

gnibbler提出了一个观点,仅仅为了副作用而使用map并不是蟒蛇式的。让我们假设make_change没有副作用,而是返回一些我想作为列表收集的内容。gnibbler指出,仅仅为了副作用而使用map不是pythonic。让我们假设make_change没有副作用,而是返回我想要收集的东西作为列表。