简体   繁体   English

当我在python中循环一个dict时会发生什么

[英]What happens when I loop a dict in python

I know Python will simply return the key list when I put a dict in for...in... syntax. 我知道当我把一个dict放入for...in...语法时, Python会简单地返回键列表。

But what what happens to the dict? 但是dict会发生什么?

When we use help(dict) , we can not see __next()__ method in the method list. 当我们使用help(dict) ,我们在方法列表中看不到__next()__方法。 So if I want to make a derived class based on dict : 所以如果我想根据dict创建一个派生类:

class MyDict(dict)
    def __init__(self, *args, **kwargs):
        super(MyDict, self).__init__(*args, **kwargs)

and return the value list with for...in... 返回值列表中的for...in...

d = Mydict({'a': 1, 'b': 2})
for value in d:

what should I do? 我该怎么办?

Naively, if all you want is for iteration over an instance of MyClass to yield the values instead of the keys, then in MyClass define: 天真地,如果你想要的只是迭代MyClass一个实例来产生值而不是键,那么在MyClass定义:

def __iter__(self):
    return self.itervalues()

In Python 3: 在Python 3中:

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

But beware! 但要小心! By doing this your class no longer implements the contract of collections.MutableMapping , even though issubclass(MyClass, collections.MutableMapping) is True. 通过这样做,您的类不再实现collections.MutableMapping的契约,即使issubclass(MyClass, collections.MutableMapping)为True。 You might be better off not subclassing dict , if this is the behaviour you want, but instead have an attribute of type dict to hold the data, and implement only the functions and operators you need. 你可能最好不要继承dict ,如果这是你想要的行为,而是有一个dict类型的属性来保存数据,并只实现你需要的函数和运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM