[英]Python: Lambda function as a namedtuple object?
I've written a program in which I have a fairly typical class. 我写了一个程序,其中我有一个相当典型的类。 In this class I create multiple namedtuple objects.
在这个类中,我创建了多个namedtuple对象。 The namedtuple objects hold many items, which all work fine, except for lambda functions that I try to bind to it.
namedtuple对象包含许多项目,除了我尝试绑定到它的lambda函数之外,它们都工作正常。 Below is a stripped down example and the error message that I am receiving.
下面是一个精简的示例和我收到的错误消息。 Hope someone knows why this is going wrong.
希望有人知道为什么会出错。 Thanks in advance!
提前致谢!
FILE: test.py 文件: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: equations.py FILE:equations.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)`
The namedtuple()
constructor returns a class , not an instance itself. namedtuple()
构造函数返回一个类 ,而不是实例本身。 You are adding methods to that class. 您正在向该类添加方法 。 As such, your lambda's must accept a
self
argument. 因此,你的lambda必须接受
self
论证。
In any case, you should create instances of the named tuple class you created. 无论如何,您应该创建您创建的命名元组类的实例。 If you don't want to give your lambdas a
self
first argument, adding them to the instance you then created would work fine: 如果你不想让你的lambdas成为
self
第一个参数,那么将它们添加到你创建的实例中就可以了:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.