setattr

Python: inconsistence in the way you define the function __setattr__?

Python: inconsistence in the way you define the function __setattr__? Question: Consider this code: class Foo1(dict): def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value class Foo2(dict): __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ o1 = Foo1() o1.x = 42 print(o1, o1.x) o2 = Foo2() o2.x = 42 print(o2, o2.x) I would expect …

Total answers: 4

How do I call setattr() on the current module?

How do I call setattr() on the current module? Question: What do I pass as the first parameter “object” to the function setattr(object, name, value), to set variables on the current module? For example: setattr(object, “SOME_CONSTANT”, 42); giving the same effect as: SOME_CONSTANT = 42 within the module containing these lines (with the correct object). …

Total answers: 4