Python中类对象自带的__str__函数

__str__是Python中类对象自带的一个函数,正常情况下,我们实例化对象后,print对象,输出的是这个对象的地址.

class Person(object):
	def __init__(self, name='Tom', age=10):
		self.name = name
		self.age = age
tom = Person()
print(tom)
# >>> <__main__.Person object at 0x00000244B4A2EA90>

而通过自定义__str__()函数,可以帮我们打印对象中的内容。

class Person(object):
	def __init__(self, name='Tom', age=10):
		self.name = name
		self.age = age
	
	def __str__(self):
		return f"your name is {
      
      self.name}"
tom = Person()
print(tom)
# >>> your name is Tom

猜你喜欢

转载自blog.csdn.net/qq_30129009/article/details/129063382