Implementation of NoneType, Reasons and Details

后端 未结 4 1154
灰色年华
灰色年华 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:32

    Why is n the exact same Object as None?

    Many immutable objects in Python are interned including None, smaller ints, and many strings.

    Demo:

    >>> s1='abc'
    >>> s2='def'
    >>> s3='abc'
    >>> id(s1)
    4540177408
    >>> id(s3)
    4540177408    # Note: same as s1
    >>> x=1
    >>> y=2
    >>> z=1
    >>> id(x)
    4538711696
    >>> id(z)
    4538711696    # Note: same as x
    

    Why was the language designed such that n is the exact same Object as None?

    See above -- speed, efficiency, lack of ambiguity and memory usage among other reasons to intern immutable objects.

    How would one even implement this behavior in python?

    Among other ways, you can override __new__ to return the same object:

    class Singleton(object):
        _instance = None
        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Singleton, cls).__new__(
                                    cls, *args, **kwargs)
            return cls._instance
    

    For strings, you can call intern on Python 2 or sys.intern on Python 3

提交回复
热议问题