Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.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,下面列出了5个参数。对于我要声明的每个参数MyClass实例: class MyClass(object): def __init__(self, arg): super(MyClass, self).__init__() self.arg = arg args=[1,2,3,4,5] instanceList=[] for arg in args: inst=MyClass(arg) instanceList.append(inst)

下面列出了5个参数。对于我要声明的每个参数
MyClass
实例:

class MyClass(object):
    def __init__(self, arg):
        super(MyClass, self).__init__()
        self.arg = arg

args=[1,2,3,4,5]

instanceList=[]
for arg in args:
    inst=MyClass(arg)
    instanceList.append(inst)
对于这样一个简单的参数列表,速度不是一个因素。但在现实世界中,参数列表可能非常庞大。 我想知道一个代码是否可以设计成一个完整的列表作为参数提交。然后返回声明的类实例列表(每个arg一个类实例),以获得速度和效率

稍后编辑: 以下是使用建议方法进行的测试:

import time
number=1000000
def method1():
    start=time.time()
    instanceList=[]
    for i in range(number):
        instanceList.append(MyClass(i))
    end=time.time()
    elapsed=end-start
    print 'method1: %s sec'%elapsed

def method2():
    start=time.time()
    instanceList=[MyClass(i) for i in range(number)]
    end=time.time()
    elapsed=end-start
    print 'method2: %s sec'%elapsed

def method3():
    start=time.time()
    instanceList = map(MyClass, range(number))
    end=time.time()
    elapsed=end-start
    print 'method3: %s sec'%elapsed

result=method1()
result=method2()
result=method3()
==========

结果:
你在找这个吗?我不确定你会看到什么样的效率提升

instanceList = [MyClass(arg) for arg in args]
甚至可能:

instanceList = map(MyClass, args)
是的,其中一些速度比其他速度快,但还不够重要:

import timeit

setup='''
class MyClass(object):
    def __init__(self, arg):
        super(MyClass, self).__init__()
        self.arg = arg
args=[1,2,3,4,5]
'''

action1='''
instanceList=[]
for arg in args:
    inst=MyClass(arg)
    instanceList.append(inst)
'''
action2='''instanceList=[MyClass(arg) for arg in args]'''
action3='''map(instanceList=MyClass, args)'''

print timeit.timeit(action1, setup, number=int(1e6)) / 1e6
print timeit.timeit(action2, setup, number=int(1e6)) / 1e6
print timeit.timeit(action3, setup, number=int(1e6)) / 1e6
结果:

3.40896606445e-06
3.00701594353e-06
2.68505501747e-06

“将整个列表作为参数提交”给什么?你的意思是对类,比如做<代码> MyClass(ARGs)< /代码>?不管你做什么,你都必须调用构造函数<代码> LAR[ARG] 倍。这个方法会导致更快的代码执行吗?对于这样一个简单的表达式,你可以考虑使用而不是列表理解。注意,在Python3中,
map
是一个生成器,因此在您使用它之前,它实际上不会创建任何实例<代码>列表(map(MyClass,args))的工作原理类似于Python 2的
map
3.40896606445e-06
3.00701594353e-06
2.68505501747e-06