Python study notes (9): the usage of __str__() method

1. The __str__() method is not defined. When using print to directly output an object, the memory address of the object is printed by default

The sample code is as follows:

# 定义一个类
class Person(object):
    # 构造方法
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 实例化一个对象
p = Person("allan", 25)
# 当使用print输出对象的时候,默认打印的是对象的内存地址:<__main__.Person object at 0x00000263CD9A5FD0>
print(p)

2. The __str__() method is defined, when the print output object is used, the data returned from this method will be printed

The sample code is as follows:

'''
__str__()方法:该没有没有参数,只有一个返回值,而且返回值是一个字符串
'''
# 定义一个类
class Person(object):
    # 构造方法
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 定义__str__()方法,当使用print输出对象的时候,就会打印从这个方法中return的数据
    def __str__(self):
        return "我的名字叫{},年龄{}".format(self.name, self.age)

# 实例化一个对象
p = Person("allan", 25)
# 输出:我的名字叫allan,年龄25
print(p)

 

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/114197801