Lambda函数在python中的类? [英] Lambda function for classes in python?

查看:83
本文介绍了Lambda函数在python中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须有一种简单的方法来执行此操作,但是我可以用某种方式将其包裹住.我可以描述我想要的最好的方法是一个类的lambda函数.我有一个库,希望将未实例化的类版本用作参数.然后,实例化该类本身以进行处理.问题是我希望能够动态创建该类的版本并传递给该库,但是由于该库需要一个未实例化的版本,所以我不知道该怎么做.下面的代码描述了该问题:

There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figure out how to do it since the library expects an uninstantiated version. The code below describes the problem:

class Double:
    def run(self,x):
        return x*2

class Triple:
    def run(self,x):
        return x*3

class Multiply:
    def __init__(self,mult):
        self.mult = mult
    def run(self,x):
        return x*self.mult

class Library:
    def __init__(self,c):
        self.c = c()
    def Op(self,val):
        return self.c.run(val)

op1 = Double
op2 = Triple
#op3 = Multiply(5)

lib1 = Library(op1)
lib2 = Library(op2)
#lib3 = Library(op3)

print lib1.Op(2)
print lib2.Op(2)
#print lib3.Op(2)

我不能使用通用的Multiply类,因为我必须首先实例化它,这会破坏库"AttributeError:Multiply实例没有 call 方法".在不更改Library类的情况下,有没有办法做到这一点?

I can't use the generic Multiply class, because I must instantiate it first which breaks the library "AttributeError: Multiply instance has no call method". Without changing the Library class, is there a way I can do this?

推荐答案

根本不需要lambda. lambda只是定义功能并同时使用它的语法糖.就像任何lambda调用都可以用显式def代替一样,我们可以通过创建一个满足您需求的真实类并返回它来解决您的问题.

There's no need for lambda at all. lambda is just syntatic sugar to define a function and use it at the same time. Just like any lambda call can be replaced with an explicit def, we can solve your problem by creating a real class that meets your needs and returning it.

class Double:
        def run(self,x):
            return x*2

class Triple:
    def run(self,x):
        return x*3

def createMultiplier(n):
    class Multiply:
        def run(self,x):
            return x*n
    return Multiply

class Library:
    def __init__(self,c):
        self.c = c()
    def Op(self,val):
        return self.c.run(val)

op1 = Double
op2 = Triple
op3 = createMultiplier(5)

lib1 = Library(op1)
lib2 = Library(op2)
lib3 = Library(op3)

print lib1.Op(2)
print lib2.Op(2)
print lib3.Op(2)

这篇关于Lambda函数在python中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆