Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据变量数量创建不同的类类型_Python - Fatal编程技术网

Python 如何根据变量数量创建不同的类类型

Python 如何根据变量数量创建不同的类类型,python,Python,我想介绍一些python代码: list1 = [] list2 = [] list3 = [] . . . for s in list3: if object in list1: e = Class1(arg1, arg2, s) else: e = Class2(arg3, arg4, arg5, s) x(e) y(e) z(e) 我想替换IF语句,这样我就可以将FOR循环和body放在一个方法中并传入e,即使它

我想介绍一些python代码:

list1 = []
list2 = []
list3 = []
.
.
.
for s in list3:

    if object in list1:
        e = Class1(arg1, arg2, s)
    else:
        e = Class2(arg3, arg4, arg5, s)

    x(e)
    y(e)
    z(e)
我想替换IF语句,这样我就可以将FOR循环和body放在一个方法中并传入e,即使它可以是两个类中的一个:

def my_method(self, list, e):

    for object in list:
        x(e)
        y(e)
        z(e)
然后只需调用我的_方法两次,一次用于list1,另一次用于list2:

# How/where do I "create" e1 and e2, given I need s, which is inside my_method()?
my_method(list1, e1)
my_method(list2, e2)
但是,我不确定如何在e中创建/传递,因为它可以表示两种不同的类类型,采用不同数量的参数,并且最后一个参数s仅在我的_方法中已知。

传递lambda

def my_method(self, list, callback):
    for object in list:
        e = callback(object)
        x(e)
        y(e)
        z(e)

my_method(list1, lambda s: Class1(arg1, arg2, s))
my_method(list2, lambda s: Class2(arg3, arg4, arg5, s))

嗨,我需要什么版本的Python来实现这一点?我不知道,我认为这是非常标准的东西。可能是,我不经常使用Python。这个答案中的所有内容都可以在任何最新版本的Python中使用。lambda关键字自1994年1月发布的1.0版以来一直使用该语言。@user997112我以为你在问,因为它不适合你。