__str__的用法
在python中方法名如果是__xxxx__()的,那么就有特殊的功能,因此叫做“魔法”方法
當使用print輸出對象的時候,只要自己定義了__str__(self)方法,那么就會打印從在這個方法中return的數據
e.g1
class Cat:
"""定義了一個Cat類"""
#初始化對象
def __init__(self, new_name, new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return "%s的年齡是:%d"%(self.name, self.age)
#創建一個對象
tom = Cat("湯姆", 40)
lanmao = Cat("藍貓", 10)
print(tom)
print(lanmao)
e.g2
class Book:
def __init__(self, name, author, comment, state = 0):
self.name = name
self.author = author
self.comment = comment
self.state = state
# 創建一個Book類的子類 FictonBook
class FictonBook(Book):
def __init__(self,name, author, comment, state = 0,type = '虛構類'):
self.type = type
Book.__init__(self, name, author, comment, state = 0)
# 繼承并定制父類的初始化方法,增加默認參數 type = '虛構類',讓程序能夠順利執行。
def __str__(self):
status = '未借出'
if self.state == 1:
status = '已借出'
return '類型:%s 名稱:《%s》 作者:%s 推薦語:%s\n狀態:%s ' % (self.type, self.name, self.author, self.comment, status)
book = FictonBook('囚鳥','馮內古特','我們都是受困于時代的囚鳥')
print(book)
'''
讓打印的結果為:
類型: 虛構類 名稱:《囚鳥》 作者:馮內古特 推薦語:我們都是受困于時代的囚鳥
狀態:未借出
'''
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
