>>> classC(): ... def__repr__(self): ... return'c' ... >>> c = C() >>> c c >>> print(c) c
虽然没有定义 __str__(), 但是两种方法都能打印出 c
同时定义了两者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
>>> classD(): ... def__str__(self): ... return'__str__ d' ... def__repr__(self): ... return'__repr__ d' ... >>> d = D(): File "<stdin>", line 1 d = D(): ^ SyntaxError: invalid syntax >>> d = D() >>> d __repr__ d >>> print(d) __str__ d
定义方法
有一个偷懒的定义repr的方法:
1 2 3 4 5 6 7 8 9 10
>>> classPerson(object): ... def__str__(self): ... return'Person' ... __repr__ = __str__ ... >>> p = Person() >>> p Person >>> print(p) Person
>>> classE(): ... def__repr__(self): ... return str(self) ... >>> e = E() >>> e Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in __repr__ File "<stdin>", line 3, in __repr__ File "<stdin>", line 3, in __repr__ [Previous line repeated 196 more times] RecursionError: maximum recursion depth exceeded while calling a Python object