如何在类中迭代`dict`,就像只提到`dict`一样?

时间:2015-03-13 13:18:35

标签: python python-3.x dictionary iterator

在定义的对象中,一些值保存在dict中,我希望迭代dict中的内容,就像引用普通dict时一样,因此可以直接访问使用[],并使用例如循环.items()。代码结构是:

class Klass:

    def __init__(self, values):
        self.values = values
        self.more = None

    def __getitem__(self, name):
        return self.values[name]

    def __iter__(self):
        pass  # TBD[How to make this ?]

d = {'alfa': 1, 'bravo': 2, 'charlie': 3}

k = Klass(d)

for key in k:
    print(key)  # Expected to print keys from self.values 

for (key, value) in k.items():
    print(key, value)  # Expected to print key and value from self.values 

for key in k.keys():
    print(key)  # Expected to print key from self.values 

for value in k.values():
    print(value)  # Expected to print value from self.values 

如何编写__iter__和其他必需的方法,以便通过Klass实例进行这种访问?

2 个答案:

答案 0 :(得分:8)

您必须自己实施.keys().values().items()方法;与__iter__一起,他们都可以将实际工作委托给self.values()词典:

class Klass:
    def __init__(self, values):
        self._values = values
        self.more = None

    def __getitem__(self, name):
        return self._values[name]

    def __iter__(self):
        return iter(self._values)

    def keys(self):
        return self._values.keys()

    def items(self):
        return self._values.items()

    def values(self):
        return self._values.values()

我重命名了该属性以避免屏蔽.values()方法。

__iter__委托给字典上的迭代(通过键)的最简单方法是使用iter() function来获取字典对象的迭代器。

要明确:__iter__在如何处理.keys().values().items()方面不起作用;后者只是更多方法

答案 1 :(得分:1)

    class Klass(dict):
        def __init__(self, *arg, **kw):
            super(Klass, self).__init__(*arg, **kw)
            self.choosebettername = super(Klass, self).keys()

        def __iter__(self):
            return iter(self.choosebettername)

        def keys(self):
            return self.choosebettername

        def itervalues(self):
            return (self[key] for key in self)


    d = {'alfa': 1, 'bravo': 2, 'charlie': 3}

    k = Klass(d)

    for key in k:
        print(key)  # Expected to print keys from self.values 

    for (key, value) in k.items():
        print(key, value)  # Expected to print key and value from self.values 

    for key in k.keys():
        print(key)  # Expected to print key from self.values 

    print(k.values())

    for value in k.values():
        print(value)  # Expected to print value from self.values