记录我的学习之旅第36天

发布: (2025年12月21日 GMT+8 02:38)
2 min read
原文: Dev.to

Source: Dev.to

我今天做了什么

  • 学习了 Python 中的 dunder(魔术)方法。

魔术方法 / Dunder 方法

Python 提供了许多特殊方法,它们的名称以双下划线开头并以双下划线结尾(__)。
你可以运行以下代码查看完整列表:

print(dir(object))

下面是两个常用的 dunder 方法:

__init__

__init__ 方法允许在对象创建时初始化其属性。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

__str__

__str__ 方法定义对象的字符串表示形式,str(obj) 会返回该表示,并在 print 时使用。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name}, {self.age} years old"

使用 dunder 方法的好处在于它们会被 Python 自动调用,无需手动显式调用。

我使用的资源

  • Python Refresher Series,作者 Bonaventure Ogeto(YouTube)
  • GitHub,用于记录并推送到我的公共仓库

接下来要做的

  • 继续学习 Python 面向对象基础 – 第 2 部分
Back to Blog

相关文章

阅读更多 »