python - 为什么 Python 2.7 namedtuple 实现了 __dict__?

标签 python python-2.7 oop

Python 2.7 中的namedtuple 实现实现了__dict__。我很困惑这是在做什么;如果已经定义了属性,为什么我们需要制作一个特殊的 __dict__

C:\tmp> python
Python 2.7.12 |Anaconda 4.1.1 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import collections
>>> x = collections.namedtuple('foo','bar baz', verbose=True)
class foo(tuple):
    'foo(bar, baz)'

    __slots__ = ()

    _fields = ('bar', 'baz')

    def __new__(_cls, bar, baz):
        'Create new instance of foo(bar, baz)'
        return _tuple.__new__(_cls, (bar, baz))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new foo object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'foo(bar=%r, baz=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new foo object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('bar', 'baz'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    bar = _property(_itemgetter(0), doc='Alias for field number 0')

    baz = _property(_itemgetter(1), doc='Alias for field number 1')

最佳答案

他们只是觉得这样会很方便。结果是 more hassle than it was worth ,导致酸洗和子类出现问题,而且它在概念上令人困惑。较新的 Python 版本不再包含它。

关于python - 为什么 Python 2.7 namedtuple 实现了 __dict__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42014207/

相关文章:

python-2.7 - 对使用 Python 2.7 和 Python 3.4 之间的不同结果感到困惑

c# - 从 C# 过渡到 C++,好的引用资料?

c++ - 为什么在接口(interface)中定义私有(private)成员/方法?

python - 如何在 Python 中使用位图 header ?

python - 矩阵处理的 RAM 要求

python - 根据python中的条件索引添加子列表元素

c# - 使用实现而不是抽象或更改实现是否正确?

Python正则表达式忽略日期模式

python - 使用核心 SQLAlchemy 插入和更新

python - 索引错误 : tuple index out of range ----- Python