Python中特殊函数__str__()

在类中定义了__str__(self)方法,那么当使用print打印实例对象的时候,就会直接打印出在这个方法中return的数据.

案列:

 1 class Book:
 2 
 3     def __init__(self, name, author, comment, state = 0):
 4         self.name = name
 5         self.author = author
 6         self.comment = comment
 7         self.state = state
 8 
 9     def __str__(self):  # 特殊函数__str__
10         if self.state == 0:
11             status = '未借出'
12         else:
13             status = '已借出'
14         return '名称:《%s》 作者:%s 推荐语:%s\n状态:%s ' % (self.name, self.author, self.comment, status)
15 
16 book1 = Book('像自由一样美丽','林达','你要用光明来定义黑暗,用黑暗来定义光明')
17 # 传入参数,创建实例对象
18 print(book1)
19 # 直接打印对象即可,不能写成print(book1.__str__())

执行结果:

名称:《像自由一样美丽》,作者:林达,你要用光明来定义黑暗,用黑暗来定义光明

状态:未借出

猜你喜欢

转载自www.cnblogs.com/Through-Target/p/12119671.html