Python: Lambda function as namedtuple object?

I wrote a program in which I have a fairly typical class. In this class, I create several namedtuple objects. Namedtuple objects contain many elements, all of which work fine, except for the lambda functions that I am trying to bind to it. Below is a stripped-down example and the error message I get. I hope someone knows why this is not happening. Thanks in advance!

FILE: test.py

from equations import * from collections import namedtuple class Test: def __init__(self, nr): self.obj = self.create(nr) print self.obj.name print self.obj.f1(2) def create(self, nr): obj = namedtuple("struct", "name f1 f2") obj.name = str(nr) (obj.f1, obj.f2) = get_func(nr) return obj test = Test(1) 

FILE: equation.py

 def get_func(nr): return (lambda x: test1(x), lambda x: test2(x)) def test1(x): return (x/1) def test2(x): return (x/2) 

Error:

 Traceback (most recent call last): File "test.py", line 17, in <module> test = Test(1) File "test.py", line 8, in __init__ print self.obj.f1(2) TypeError: unbound method <lambda>() must be called with struct instance as first argument (got int instance instead)` 
+4
source share
1 answer

The namedtuple() constructor returns the class, not the instance itself. You add methods to this class. So your lambda should take a self argument.

In either case, you need to instantiate the type of named tuple you created. If you don't want your lambdas to give the first self argument, adding them to the instance you created will work fine:

 from equations import * from collections import namedtuple Struct = namedtuple("struct", "name f1 f2") class Test: def __init__(self, nr): self.obj = self.create(nr) print self.obj.name print self.obj.f1(2) def create(self, nr): obj = Struct(str(nr), *get_func(nr)) return obj test = Test(1) 
+4
source

All Articles