Instance variables vs. class variables in Python

后端 未结 4 850
我在风中等你
我在风中等你 2020-11-22 05:32

I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there woul

4条回答
  •  旧巷少年郎
    2020-11-22 06:20

    Same question at Performance of accessing class variables in Python - the code here adapted from @Edward Loper

    Local Variables are the fastest to access, pretty much tied with Module Variables, followed by Class Variables, followed by Instance Variables.

    There are 4 scopes you can access variables from:

    1. Instance Variables (self.varname)
    2. Class Variables (Classname.varname)
    3. Module Variables (VARNAME)
    4. Local Variables (varname)

    The test:

    import timeit
    
    setup='''
    XGLOBAL= 5
    class A:
        xclass = 5
        def __init__(self):
            self.xinstance = 5
        def f1(self):
            xlocal = 5
            x = self.xinstance
        def f2(self):
            xlocal = 5
            x = A.xclass
        def f3(self):
            xlocal = 5
            x = XGLOBAL
        def f4(self):
            xlocal = 5
            x = xlocal
    a = A()
    '''
    print('access via instance variable: %.3f' % timeit.timeit('a.f1()', setup=setup, number=300000000) )
    print('access via class variable: %.3f' % timeit.timeit('a.f2()', setup=setup, number=300000000) )
    print('access via module variable: %.3f' % timeit.timeit('a.f3()', setup=setup, number=300000000) )
    print('access via local variable: %.3f' % timeit.timeit('a.f4()', setup=setup, number=300000000) )
    

    The result:

    access via instance variable: 93.456
    access via class variable: 82.169
    access via module variable: 72.634
    access via local variable: 72.199
    

提交回复
热议问题