I am subclassing a dict and would love some help understanding the behavior below (please) [Python version: 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))
Produces this output:
{'a': 'x1', 'b': 'x2'}
in __getitem__
in __getitem__
{'a': 'x1', 'b': 'x2'}
If I comment out the __iter__
method the output changes like so:
{'a': 'x1', 'b': 'x2'}
{'a': 1, 'b': 2}
Obviously the __iter__
method is not getting called, however its presence is affecting the behaviour.
I am just interested in why this happens. I am not looking for alternative solutions to prevent it.
Thanks, Paul.