Python属性将属性名称的错误函数关联起来

时间:2017-01-12 15:25:07

标签: python python-2.7 lambda properties descriptor

我正在实施一个简单的命名元组' type机制,它具有只读属性而不是读/写。

def ReadOnlyNamedTuple( *fields ):
    class Base( object ):
        _fields = fields[:]
        def __init__( self, *values ):
            assert len(values) == len(Base._fields), "Incorrect number of arguments, expected %d" % len(Base._fields) 
            self._field_values = dict( zip( Base._fields, values ) )
        def __getitem__( self, i ):
            return self._field_values[ Base._fields[i] ]
        def __len__(self):
            return len( self._field_values )
    # attach the fields to the class with properties:
    for attr in fields :
        fn = lambda s : s._field_values[attr]
        fn = property( fn )
        setattr( Base, attr, fn )
    return Base

当我执行此操作时,最后一个" getter" lambda函数似乎附加到所有属性。

>>>                                                                     
>>> C = ReadOnlyNamedTuple( 'a','b','c' )                                        
>>> c = C( 1, 2, 3 )                                                    
>>> c[0]                                                                
1                                                                       
>>> c[1]                                                                
2                                                                       
>>> c[2]                                                                
3                                                                       
>>> c.a                                                                 
3                                                                       
>>> c.b                                                                 
3                                                                       
>>> c.c                                                                 
3                                                                       
>>> c._field_values                                                     
{'a': 1, 'c': 3, 'b': 2}   

看起来很傻,但我无法弄清楚为什么属性没有正确附加。建议?

0 个答案:

没有答案