相关疑难解决方法(0)

如何使用__getitem__和__iter__并从字典中返回值?

我有一个带有字典的对象,我想通过__getitem__它来访问并迭代(仅值,键无关紧要),但我不知道该怎么做.

例如:

Python 2.5.2 (r252:60911, Jul 22 2009, 15:33:10) 
>>> class Library(object):
...   def __init__(self):
...     self.books = { 'title' : object, 'title2' : object, 'title3' : object, }
...   def __getitem__(self, i):
...     return self.books[i]
... 
>>> library = Library()
>>> library['title']
<type 'object'>
>>> for book in library:
...   print book
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __getitem__
KeyError: 0
>>> 
Run Code Online (Sandbox Code Playgroud)

如何告诉它只需返回object字典中的每个项目(键无关紧要)?

python iterator

15
推荐指数
1
解决办法
3万
查看次数

仅当定义了 __iter__ 时才会调用 __getitem__

我正在对一个字典进行子类化,并且希望获得一些帮助来理解下面的行为(请)[Python 版本:3.11.3]:

class Xdict(dict):
    def __init__(self, d):
        super().__init__(d)
        self._x = {k: f"x{v}" for k, v in d.items()}

    def __getitem__(self, key):
        print("in __getitem__")
        return self._x[key]

    def __str__(self):
        return str(self._x)

    def __iter__(self):
        print("in __iter__")

d = Xdict({"a": 1, "b": 2})
print(d)
print(dict(d))
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

{'a': 'x1', 'b': 'x2'}
in __getitem__
in __getitem__
{'a': 'x1', 'b': 'x2'}
Run Code Online (Sandbox Code Playgroud)

如果我注释掉该__iter__方法,输出会像这样改变:

{'a': 'x1', 'b': 'x2'}
{'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)

显然该__iter__方法没有被调用,但它的存在正在影响行为。

我只是对为什么会发生这种情况感兴趣。我并不是在寻找替代解决方案来防止它。

谢谢,保罗。

python dictionary subclass

2
推荐指数
1
解决办法
105
查看次数

标签 统计

python ×2

dictionary ×1

iterator ×1

subclass ×1