21 Jan 2010

Python Tips-实现dict类似class的点操作符

实现dict类似class的点操作符
通过dict['name']或者dict.name取得value.
来自cn.python: Jiahua Huang



class Storage(dict):
    def __new__(cls, *args, **kwargs):
        self = dict.__new__(cls, *args, **kwargs)
        self.__dict__ = self
        return self

>>> student = Storage( )
>>> student['name'] = 'XXOO'
>>> student.name

'XXOO' 


No comments :

Post a Comment