I am reading DiveIntoPython.
I’m wondering why I can directly print the instance of a UserDict as a dictionary.
In detail, these codes
import UserDict;
d = UserDict.UserDict({1:1, 'a':2});
print d;
print d.data;
will have output
{'a': 2, 1: 1}
{'a': 2, 1: 1}
And these codes
class MyDict:
def __init__(self, dictData=None):
self.data = dictData;
d = MyDict({1:1, 'a':2});
print d;
print d.data;
will have output (on my machine)
<__main__.MyDict instance at 0x10049ef80>
{'a': 2, 1: 1}
In other words, How I can define my class, and print its instances as a built-in datatype?
Thank you!
How an object is printed comes down to it’s
repr– when you inherit from a mixin, it already provides thereprfunction. Also note, these days you can just inherit fromdictdirectly.In your case, you can define
The difference between
__str__and__repr__is that mostly__str__should be readable and understable.__repr__where it’s possible can be used to provide aneval‘d string constructing the original object (although not necessary) – see the great answer here for the difference: Difference between __str__ and __repr__ in Python