[Python] In the dict class, why does the update method not call __setitem__? [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    Very simple example:

    class MyDict(dict):
    def __setitem__(self, key, value):
    print(f"setting new dictionary item {key}:{value}.")
    return super().__setitem__(key, value)

    d1 = MyDict(a=100, b=200)
    d1.update(c=300)
    d1['d'] = 400


    I would have expected the message for setting c:300 to be printed, but it isn't, it's printed only for d:400. I would have expected the update method to call setitem. Why is this expectation mistaken?

    Continue reading...

Compartilhe esta Página