Python的其他方法
1 __str__方法
触发时机: 使用print(对象)或者str(对象)的时候触发
功能: 查看对象信息
参数: 一个self接受当前对象
返回值: 必须返回字符串类型
基本用法
创建一个基本的类
class Cat():
gift = "catch mouse"
def __init__(self,name):
self.name = name
def cat_info(self):
strvar = "This object is {},and cat can catch {} normally".format(self.name,self.gift)
return strvar
tom = Cat("Tom")
res = tom.cat_info()
print (res)
print (tom)
使用__str__定义属性查看
class Cat():
gift = "catch mouse"
def __init__(self,name):
self.name = name
def cat_info(self):
strvar = "This object is {},and cat can catch {} normally".format(self.name,self.gift)
return strvar
def __str__(self):
return "strcgdfas" #必须要返回一个字符串
tom = Cat("Tom")
res = tom.cat_info()
print (res)
print (tom)
不返回字符串报错
class Cat():
gift = "catch mouse"
def __init__(self,name):
self.name = name
def cat_info(self):
strvar = "This object is {},and cat can catch {} normally".format(self.name,self.gift)
return strvar
def __str__(self):
return 1234
tom = Cat("Tom")
res = tom.cat_info()
print (res)
print (tom)
执行