Re: use of dict() function

Alex Kleider <[email protected]> Wed, 12 Jun 2024 10:58:58 -0700
Newsgroups gmane.comp.python.tutor
Message-ID <CAMCEyD7NRf1KxT4a=t_GcKLhJqBO-QX609XbKFh-r-wOHv_v8A@mail.gmail.com>
On the contrary, I have _not_ figured it out!
My goal is to have a way of creating an object (a class instance,) in
this case a dict, without there being any chance of the original dict
(the parameter of the init call) being modified.
(... and also to have the additional feature of being able to "call"
the instance and get the dict formatted as specified by the string
parameter.)
Using the dict function provides the mechanism to do the first part
without the need of a class.
Must I assign to an intermediary identifier rather than to self itself?
i.e. self.value = dict(mapping)
and then access the mapping using "instance.value"  rather than
"instance" by itself?
Thanks for your input.
Alex


On Wed, Jun 12, 2024 at 1:11 AM Peter Otten via Tutor <[email protected]> wrote:
>
> 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



--
[email protected]  (he/him)
(sent from my current gizmo)
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor