Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Apply member function in a map

I declare a class Employee and a list consist of it:

class Employee():
    def __init__(self, _name):
        self.name = _name
    def get_name(self):
        return self.name

Tom   = Employee("Tom")
Karl  = Employee("Karl")
John  = Employee("John")

employee_list = [Tom, Karl, John]

Now I want to have a list of their name by applying get_name in a map:

name_list = map(get_name, employee_list)


Traceback (most recent call last): File "ask.py", line 13, in <module> 
    name_list = map(get_name, employee_list) 
NameError: name 'get_name' is not defined

How could get_name be not defined?

How do I do to apply member function in a map?

like image 791
J.Coder.Joe Avatar asked Apr 27 '16 07:04

J.Coder.Joe


People also ask

How do I iterate over a map object in Python?

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc.

How do you pass an index on a map in Python?

To get access to the index in the map function:Use the enumerate() function to get an object of index/item tuples. Unpack the index and item values in the function you pass to map() . The function will get passed a tuple containing the index and item on each iteration.

How do you map all elements in a list in Python?

Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.

What does map () do in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.


2 Answers

map(get_name, employee_list)in your code is equivalent to

[get_name(employee) for employee in employee_list]

not [employee.get_name() for employee in employee_list]

You should declare a get_name method outside of Employee class:

def get_name(employee):
    return employee.name

or an easier way with Lambda:

name_list = map(lambda employee: employee.name, employee_list)

like image 153
Rahn Avatar answered Sep 20 '22 22:09

Rahn


You have to call the method from the instance. You can use a lambda for this

name_list = map(lambda e: e.get_name(), employee_list)
like image 26
salomonderossi Avatar answered Sep 19 '22 22:09

salomonderossi