0

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!

DSM
  • 342,061
  • 65
  • 592
  • 494
Kaifei
  • 1,568
  • 2
  • 13
  • 16
  • 2
    As a side note -- I don't think too many python programmers enjoy looking at the semicolons at the end of the line. You can make the "They don't hurt" argument -- **And you'd be absolutely right** (until your co-worker gets tired enough of looking at them that he comes and punches you in the face) -- :-P – mgilson Jan 25 '13 at 21:00
  • @mgilson Actually, I am also struggling on whether semicolons should be used. What is the motivation of not using it? Thank you. – Kaifei Jan 25 '13 at 21:44
  • BTW, I was primarily writing C before learning python now, that is the reason that I use semicolons.... – Kaifei Jan 25 '13 at 21:46
  • They're unnecessary. Python's a very elegant language and I think that a lot of people would argue that it visually disrupts the flow of thought as you try to read the code. And, C and languages which are influenced by it are the reason most people use semicolons ;-) – mgilson Jan 25 '13 at 21:46
  • @mgilson Sounds reasonable. I'll think about it. Thank you for pointing it out. :) – Kaifei Jan 25 '13 at 21:48
  • `UserDict` hasn't been relevant for a really, really long time (and is gone in 3.x). You can and should inherit directly from the builtin `dict` instead now. (Leaving aside the question of whether you really want to inherit from a container type...) – Karl Knechtel Jan 25 '13 at 22:39

1 Answers1

3

How an object is printed comes down to it's repr - when you inherit from a mixin, it already provides the repr function. Also note, these days you can just inherit from dict directly.

In your case, you can define

def __repr__(self):
    return repr(self.data)

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 an eval'd string constructing the original object (although not necessary) - see the great answer here for the difference: Difference between __str__ and __repr__ in Python

Community
  • 1
  • 1
Jon Clements
  • 138,671
  • 33
  • 247
  • 280