How to inherit from Python None

后端 未结 3 898
夕颜
夕颜 2020-12-18 23:37

I would like to create a class that inherites from None.

Tried this:

class InvalidKeyNone(None):
    pass

but that giv

相关标签:
3条回答
  • 2020-12-18 23:55

    There's no way to do it, at least definitely not until you do some unreadable black magic.

    You should probably use exceptions.

    0 讨论(0)
  • 2020-12-18 23:57

    None is a constant, the sole value of types.NoneType (for v2.7, for v3.x)

    Anyway, when you try to inherit from types.NoneType

    from types import NoneType
    
    class InvalidKeyNone(NoneType):
        pass
    
    foo = InvalidKeyNone()
    print(type(foo))
    

    you'll get this error

    Python 2

    TypeError: Error when calling the metaclass bases type 'NoneType' is not an acceptable base type

    Python 3

    ImportError: cannot import name 'NoneType'

    in short, you cannot inherit from NoneType

    Anyway, why would want a class to inherit NoneType?

    0 讨论(0)
  • 2020-12-19 00:10

    Subclassing None does not make sense, since it is a singleton and There Can Be Only One. You say you want a class with the same behaviour, but None does not have any behaviour!

    If what you really want is a unique placeholder that you can return from a function to indicate a special case then simplest way to do this is to create a unique instance of object:

    InvalidKey = object()
    
    result = doSomething()
    if result is InvalidKey:
        ...
    
    0 讨论(0)
提交回复
热议问题