Re: use of dict() function
Peter Otten via Tutor <[email protected]> Wed, 12 Jun 2024 10:03:54 +0200
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <[email protected]> |
On 03/06/2024 04:44, Alex Kleider wrote:
You may have figured it out in the mean time, but note that
> class Rec1(dict):
> def __init__(self, rec):
> self = dict(rec)
assigning to self has no effect (on the class). self is just a name that
you can bind anything to:
>>> class Stuff:
def __init__(self):
print(f"before: {self})"
self = 42
print(f"after: {self}")
SyntaxError: invalid syntax
>>> class Stuff:
def __init__(self):
print(f"before: {self})")
self = 42
print(f"after: {self}")
>>> Stuff()
before: <__main__.Stuff object at 0x02BDD5B0>)
after: 42
<__main__.Stuff object at 0x02BDD5B0>
So you are basically overwriting dict.__init__() with a no-op
Rec1.__init__(). The easiest fix is to omit the initializer:
>>> class R(dict):
def __call__(self, fmt): return fmt.format_map(self)
>>> r = R({"a": 1}, b=2)
>>> r["c"] = 3
>>> r
{'a': 1, 'b': 2, 'c': 3}
>>> r("{a} + {b} = {c}")
'1 + 2 = 3'
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor