use of dict() function
Alex Kleider <[email protected]> Sun, 2 Jun 2024 19:44:35 -0700
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <CAMCEyD7WkNhw4nuOheEvKC9aA61x69jRzWEUL4WhLOPLJC+5jQ@mail.gmail.com> |
#!/usr/bin/env python3
"""
Question:
I created a class which I initially coded as in Rec0.
I then read[1] that calling dict(mapping) returns a new dict
essentially providing the functionality of my class (except
for the call-ability feature.)
The interesting thing is that calling dict(mapping) within a class
definition seems to result in different behavior than when called
elsewhere.
Is there an explanation???
The following code hopefully illustrates what I'm on about.
Cheers,
Alex Kleider
[1]: https://www.thepythoncodingstack.com/p/python-dict-is-more-versatile-than-you-may-think
"""
class Rec0(dict):
def __init__(self, rec):
for key, value in rec.items():
self[key] = value
def __call__(self, fstr):
return fstr.format(**self)
class Rec1(dict):
def __init__(self, rec):
self = dict(rec)
def __call__(self, fstr):
return fstr.format(**self)
def test():
d0 = {"husband": "Alex", "wife": "June",
"daughter": "Tanya", "son": "Kelly", }
d1 = dict(d0)
d1["grand_daughter"] = "Isabella"
print("Using dict function directly...")
print(" d1 should (and does) contain five entries as follows:")
print(d1); print()
d0 = {"husband": "Alex", "wife": "June",
"daughter": "Tanya", "son": "Kelly", }
d1 = Rec0(d0)
d1["grand_daughter"] = "Isabella"
print("Using Rec0 (which doesn't use the dict() function)...")
print(" d1 also contain five entries as follows:")
print(d1); print()
d0 = {"husband": "Alex", "wife": "June",
"daughter": "Tanya", "son": "Kelly", }
d1 = Rec1(d0)
d1["grand_daughter"] = "Isabella"
print("Using Rec1 (which uses the dict() function)...")
print(" d1 should (but doesn't) contain the five entries:")
print(d1); print()
if __name__ == "__main__":
test()
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor