1.调用时机
使用print打印对象的时候会使用到__str__方法 例:print(对象)
1.如果没有定义__str__方法,print(对象)则会打印对象的引用地址
2.如果自己定义了__str__方法,print(对象)则会打印方法的返回值
2.应用场景
使用print(对象)打印输出对象的属性信息
3.注意事项
必须使用return返回字符串类型
4.示例
实现:使用print打印出Cat类对象的属性信息
首先我们可以创建一个Cat类,包含有属性name&age,创建一个__init__方法来初始化每个Cat类对象的公共属性
,创建一个__str__方法来实现我们所需要实现的输出结果
1.首先我们不重写__str__方法,看看会输出什么
'''
类:Cat
属性:name,age
方法:__init__、__str__
'''
class Cat:
def __init__(self,name,age):
self.name=name
self.age=age
# def __str__(self):
# return f"{self.name},{self.age}"
tom=Cat("tom",18)
print((tom))
输出结果为tom对象的地址
重写__str__方法重新运行
'''
类:Cat
属性:name,age
方法:__init__、__str__
'''
class Cat:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return f"{self.name},{self.age}"
tom=Cat("tom",18)
print((tom))
输出结果为我们在__str__方法中返回的name&age信息
如果我们在__str__方法中不使用return返回,看看效果怎么样
'''
类:Cat
属性:name,age
方法:__init__、__str__
'''
class Cat:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
print(self.name)
# return f"{self.name},{self.age}"
tom=Cat("tom",18)
print((tom))
输出结果出现报错
提示我们__str__返回的信息类型错误,非字符串类型
接下来我们再把return加上,看看效果
'''
类:Cat
属性:name,age
方法:__init__、__str__
'''
class Cat:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
print(self.name)
return f"{self.name},{self.age}"
tom=Cat("tom",18)
print((tom))
这时则正常返回对象信息