digicoder digicoder - 5 months ago 14
Python Question

lambda,map on object arrays in python - Return List of objects

How to return a list of objects and not list here.
I want to return a list of test objects and not a list of str..

class test:
val = ""
def __init__(self,v):
self.val = v
def tolower(self,k):
k = k.val.lower()
return k

def test_run():
tests_lst = []
i_want_object_of_test = map(lambda x:x.val.lower(),tests_lst)

if __name__ == '__main__':

['test-0', 'test-1', 'test-2']

i want a list of test objects where each object's val has changed to lower case.


The question is unclear. I'll answer by what I understand.

What I understand is that you are trying to create a new list of test objects, with the values as lower case.

You can do this either by changing the state of each of the objects in a for loop (changing state is usually not recommended):

for test_obj in test_lst:
    test_obj.val = test_obj.val.lower()

A way to do it through a list comprehension is to create new test instances:

i_want_object_of_test = [test(test_obj.val.lower()) for test_obj in test_lst]

Besides, there are a few problems with your test class:

  • It is an old style class, you should always inherit from object in your classes: class test(object):
  • You define a class variable by putting val = ""' in your class defenition, you then override it in each instance.
  • Your tolower method gets another test instance (k) and returns its value as lower case. I assume you want to either return a new test object or change the current one in place. Either way the method should only use self.