What is the difference between old style and new style classes in Python?

前端 未结 8 1344
Happy的楠姐
Happy的楠姐 2020-11-21 04:48

What is the difference between old style and new style classes in Python? When should I use one or the other?

8条回答
  •  遥遥无期
    2020-11-21 05:22

    Old style classes are still marginally faster for attribute lookup. This is not usually important, but it may be useful in performance-sensitive Python 2.x code:

    In [3]: class A:
       ...:     def __init__(self):
       ...:         self.a = 'hi there'
       ...:
    
    In [4]: class B(object):
       ...:     def __init__(self):
       ...:         self.a = 'hi there'
       ...:
    
    In [6]: aobj = A()
    In [7]: bobj = B()
    
    In [8]: %timeit aobj.a
    10000000 loops, best of 3: 78.7 ns per loop
    
    In [10]: %timeit bobj.a
    10000000 loops, best of 3: 86.9 ns per loop
    

提交回复
热议问题