【人工智能概述】python妙用 __str__()

【人工智能概述】python妙用 str()


一.python内置函数__str__()

  • 通过自定义__str__()函数可以打印对象中相关的内容。
class Person(object):
    def __init__(self, name = 'tom', age = 10):
        self.name = name
        self.age = age
        self.parent = None
    
    def __str__(self):
        return "Your name is: " + self.name
    
tom = Person()
print(tom)
 
# 唔,果然输出了我们自定义的内容
# >>> Your name is: tom

猜你喜欢

转载自blog.csdn.net/qq_44928822/article/details/131733943