关于在Python中访问类变量的性能存在相同的问题-此处的代码改编自@Edward Loper
局部变量是访问最快的,与模块变量,类变量,实例变量密切相关。
您可以从以下四个范围访问变量:
- 实例变量(self.varname)
- 类变量(Classname.varname)
- 模块变量(VARNAME)
- 局部变量(变量名)
考试:
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) )
结果:
access via instance variable: 93.456
access via class variable: 82.169
access via module variable: 72.634
access via local variable: 72.199