【问题标题】:Python module __builtin__ has no attribute NoneTypePython 模块 __builtin__ 没有属性 NoneType
【发布时间】:2012-10-30 16:50:24
【问题描述】:

出于此问题范围之外的原因,我正在构建一个序列化机制。我遇到了None 对象的问题,我认为我需要特殊情况。谁能解释为什么 NoneType 与其他内置类型的处理方式不同?还是我错过了什么?

>>> import sys
>>> builtin = sys.modules['__builtin__']
>>> getattr(builtin,'int')
<type 'int'>
>>> getattr(builtin,'list')
<type 'list'>
>>> getattr(builtin,'NoneType')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'NoneType'

Ubuntu 上的 python 2.6.5

澄清

当然

getattr(builtin,'None')

工作并返回一个None 对象,它是NoneType 的一个实例。但是类对象存在于__builtin__ 模块中,用于其他所有内容。因此,此代码适用于除 None 之外的所有内置类型:

klass = getattr(builtin, obj.__class__.__name__)

这是有道理的

>>> type(0).__module__
'__builtin__'
>>> type("foo").__module__
'__builtin__'
>>> type(None).__module__
'__builtin__'

None 失败的事实似乎是 Python 中的疏忽,除非我遗漏了什么。

【问题讨论】:

  • getattr(builtin,"None") ...也许...

标签: python


【解决方案1】:

我想你所谓的NoneType 被特殊对待,因为你几乎不需要访问它。你可以说

>>> NoneType = type(None)

将此类型绑定到一个名称,但这没有共同的目的:isinstance(x, NoneType) 将与x is None 人为等效;构造函数引发TypeError 声明您不应该构造实例;并且从它派生也是被禁止的。

不过,如果您出于某些高级目的需要它,您仍然可以通过 type(None)None.__class__types.NoneType 访问该类型。

【讨论】:

    【解决方案2】:

    这很奇怪。但是关于 python 2 中的类和对象的许多奇怪的事情也是如此。从简单的脚本演变为成熟的 OO 的一堆语言都是如此。 Python 3 旨在解决这个问题。

    NoneType 已经是特例了,因为它是单例的类对象,所以不能作为构造函数调用。

    TypeError: cannot create 'NoneType' instances
    

    因此,如果您正在编写通用序列化程序,那么无论如何您都需要特殊情况 None,无论您是否无法查找类对象。

    【讨论】:

      【解决方案3】:

      您是否尝试过查看:

      >>> dir(builtin)
      ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
      

      NoneType 未列为内置类型(即使 None 是)

      【讨论】:

        【解决方案4】:

        你应该试试:getattr(builtin,"None") 而不是getattr(builtin,"NoneType"),因为NoneTypetype(None) 的值,所以它不是builtin 的属性。

        In [49]: type(None)
        
        Out[49]: <type 'NoneType'>
        

        这不起作用,因为 Python 无法在任何地方找到 NoneType

        In [50]: type(NoneType)
        ---------------------------------------------------------------------------
        NameError                                 Traceback (most recent call last)
        
        /home/monty/<ipython console> in <module>()
        NameError: name 'NoneType' is not defined
        

        【讨论】:

          【解决方案5】:

          类型模块中提供了无类型。

          >>> import types
          >>> types.NoneType
          <type 'NoneType'>
          

          如果您对类型做任何事情,Infact types 模块是使用的正确地方,不要依赖 builtins

          中存在的类型

          这可能是因为 None 不是一个真正的类型,它是一个builtin constant。甚至文档都说 None 的类型是 types.NoneType,但你是对的,它是以特殊方式实现的,并且与所有其他类型不一致。

          【讨论】:

          • 显然我不能依赖它,因为它不存在。但考虑到其他一切都在那里,它的遗漏是没有意义的。
          • @Leopd:当然有道理;为什么应该有一个内置的构造函数来创建一个已经内置的单例?
          • 我得到 AttributeError:模块 'types' 没有属性 'NoneType'
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-03-05
          • 1970-01-01
          • 1970-01-01
          • 2019-11-05
          • 2013-04-19
          • 2019-10-03
          • 2021-01-02
          相关资源
          最近更新 更多