Can I use a class instead of a function with map in Python?

According to the doc, the map function "applies function to every item of iterable and returns a list of the results". I've noticed that it also works for classes, eg map(MyClass, get_iterable()) and returns a list of the class instances.
Is this correct usage of map ?


The docs actually say “Apply function to every item of iterable” where function is a reference to the parameter name. So yes, map can be used with any callable; and all types are callable (in that they will create an object of that type).


map expects a callable. If an object is a callable, that works too:

class Foo(object):
    def __call__(self, foo):
        return foo

print map(Foo(), [1,2,3])

try it:

>>> map(str, [1,2,3])
['1', '2', '3']

the doc refers to function as the name of the argument. Its type is irrelevant - it should only be callable.

链接地址: http://www.djcxy.com/p/53582.html

上一篇: 为什么x,y = zip(* zip(a,b))在Python中起作用?

下一篇: 我可以在Python中使用类来代替函数吗?