Implementation of NoneType, Reasons and Details

后端 未结 4 1122
灰色年华
灰色年华 2021-01-11 15:53

I recently read somewhere that the special value None in python is a singleton object of its own class, specifically NoneType. This explained a lot

4条回答
  •  再見小時候
    2021-01-11 16:26

    1. The NoneType overrides __new__ which always return the same singleton. The code is actually written in C so dis cannot help, but conceptually it's just like this.

    2. Having only one None instance is easier to deal with. They are all equal anyway.

    3. By overriding __new__... e.g.

      class MyNoneType(object):
          _common_none = 0
          def __new__(cls):
              return cls._common_none
      
      MyNoneType._common_none = object.__new__(MyNoneType)
      
      m1 = MyNoneType()
      m2 = MyNoneType()
      print(m1 is m2)
      

提交回复
热议问题