[Tutor] use of dict() function
Peter Otten
__peter__ at web.de
Wed Jun 12 14:59:57 EDT 2024
On 12/06/2024 19:58, Alex Kleider wrote:
> 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.
Subclassing dict like this
class R(dict):
def __call__(self, fmt):
return fmt.format_map(self)
should do that. As R inherits from dict and does not override the
__init__() or __new__() method
r = R(some_dict)
copies some_dict's contents just like
d = dict(some_dict)
does, and provides the required formatting feature.
> 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?
Again: assigning to self has no effect. Inside the __init__() method the
R, say, instance is already created and is basically a shallow copy of
the original some_dict. At that point you only mutate r, and if you add,
remove, or replace a key some_dict will not magically change.
More information about the Tutor
mailing list