·

Python的__str__()方法

Published at 2024-08-29 11:21:32Viewed 109 times
Professional article
Please reprint with source link

Python的__str__()方法

说明:本文章的Python代码测试基于Python3.x


__str__()方法的作用:

  1. 不定义__str__方法,print输出对象实例时,默认打印对象实例的内存地址
  2. 定义__str__方法,print输出对象实例时,自动调用此方法
  3. 返回值必须是字符串
  4. 在Python中,方法名形如__xxx__()的方法表示此方法具有特殊的功能,也称为魔法方法

验证

1. 不定义__str__方法,print输出对象实例时,默认打印的是对象的内存地址

# 创建学生类
class Stu():
    def __init__(self, name, age):
        self.name = name
        self.age = age

s = Stu("张三", 18)
print(s)

输出:

<__main__.Stu object at 0x000002526AF05A60>

2. 定义__str__方法,print输出对象实例时,自动调用此方法

class Stu():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return "学生" + self.name + "的年龄是" + str(self.age)

s = Stu("张三", 18)
# 打印对象实例
print(s) 

输出:

学生张三的年龄是18

3. 返回值必须是字符串

class Stu():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return self.age

s = Stu("张三", 18)
print(s)

输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      7 
      8 s = Stu("张三", 18)
----> 9 print(s)

TypeError: __str__ returned non-string (type int)

因为__str__()返回值非字符串,所以报错TypeError: __str__ returned non-string (type int)


原文链接:https://blog.csdn.net/what_how_why2020/article/details/114748495

Comments

There is no comment, let's add the first one.

弦圈热门内容

[antd: Message] You are calling notice in render which will break in React 18 concurrent mode. Please trigger in effect instead.

I'm getting this error when using MessageWarning: [antd: Message] You are calling notice in render which will break in React 18 concurrent mode. Please trigger in effect instead.Here is my code:import { message } from 'antd'; export default function Page() { const [messageApi, contextHolder] = message.useMessage(); const res = await fetch("/api/...", { method: "POST", }); if (!res.ok) { messageApi.error("Error! Fail to login!"); } return ( &lt;Home&gt; ... &lt;/Home&gt; ) }

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved