开发者

Avoiding unncessary use of lambda for calls to object methods

Consider the following code, which simply calls a method on each member of a list:

class Demo:
    def make_change(self):
        pass

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

Is there a way to accomplish this without the long-winded lambda syntax? For example, in Scala, something similar to map(_.make_change(), foo) works. Does Python have an开发者_StackOverflow社区 equivalent?


It's not very pythonic to use map just for side-effects

so why not

for item in foo:
    item.make_change()

This will run faster than using map

you can put it on one line if you insist, but I wouldn't

for item in foo:item.make_change()


operator.methodcaller('make_change')


I'm with gnibbler on the pythonicity. Apart from that, this is also possible:

map(Demo.make_change, foo)

It has problems, though:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜