30-Python内置方法之__str__和__repr__

定义一个类,然后实例化,观察打印结果:

 1 >>> class Person(object):
 2 ...     def __init__(self, name, age):
 3 ...         self.name = name
 4 ...         self.age = age
 5 ...         
 6 >>> p = Person("druid", 18)
 7 >>> p
 8 <Person object at 0x11044b160>  # 直接调用对象打印的是内存地址
 9 >>> print(p)
10 <Person object at 0x11044b160>  # 用print打印仍然是内存地址

 

在类中增加__str__方法,观察打印结果:

 1 >>> class Person(object):
 2 ...     def __init__(self, name, age):
 3 ...         self.name = name
 4 ...         self.age = age
 5 ... 
 6 ...     def __str__(self):
 7 ...         return "{}-{}".format(self.name, self.age)
 8 ...     
 9 >>> p1 = Person("druid", 18)
10 >>> p1
11 <Person object at 0x1105899e8>  # 直接调用对象打印的是内存地址
12 >>> print(p1)
13 druid-18  # 用print打印的是__str__返回的string

 

在类中增加__repr__方法,观察打印结果:

 1 >>> class Person(object):
 2 ...     def __init__(self, name, age):
 3 ...         self.name = name
 4 ...         self.age = age
 5 ... 
 6 ...     def __repr__(self):
 7 ...         return "{}-{}".format(self.name, self.age)
 8 ...     
 9 >>> p2 = Person("druid", 18)
10 >>> p2
11 druid-18  # 直接调用对象打印的是__repr__返回的string
12 >>> print(p2)
13 druid-18  # 用print打印仍然是__repr__返回的string

 

posted @ 2018-07-18 15:00  Druid_Py  阅读(182)  评论(0编辑  收藏  举报