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

前端 未结 8 1338
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:24

    Here's a very practical, true/false difference. The only difference between the two versions of the following code is that in the second version Person inherits from object. Other than that, the two versions are identical, but with different results:

    1. Old-style classes

      class Person():
          _names_cache = {}
          def __init__(self,name):
              self.name = name
          def __new__(cls,name):
              return cls._names_cache.setdefault(name,object.__new__(cls,name))
      
      ahmed1 = Person("Ahmed")
      ahmed2 = Person("Ahmed")
      print ahmed1 is ahmed2
      print ahmed1
      print ahmed2
      
      
      >>> False
      <__main__.Person instance at 0xb74acf8c>
      <__main__.Person instance at 0xb74ac6cc>
      >>>
      
      
    2. New-style classes

      class Person(object):
          _names_cache = {}
          def __init__(self,name):
              self.name = name
          def __new__(cls,name):
              return cls._names_cache.setdefault(name,object.__new__(cls,name))
      
      ahmed1 = Person("Ahmed")
      ahmed2 = Person("Ahmed")
      print ahmed2 is ahmed1
      print ahmed1
      print ahmed2
      
      >>> True
      <__main__.Person object at 0xb74ac66c>
      <__main__.Person object at 0xb74ac66c>
      >>>
      

提交回复
热议问题