Python 魔法方法 (Magic Methods)
大家好!今天我们来聊聊Python的魔法方法。
魔法方法,也叫dunder方法,是Python中一些特殊的方法,它们以双下划线开头和结尾,比如__init__
、__str__
等等。
这些方法可以让你控制类的行为,让你的对象支持各种操作,比如加法、比较、打印等等。
举个例子,我们定义一个Book类,有title、author和pages三个属性。
__init__
方法是构造函数,用来初始化对象。
__str__
方法可以定义对象在打印时的输出。
__len__
方法可以定义对象的长度。
__add__
方法可以定义对象之间的加法操作。
通过这些魔法方法,我们可以让我们的类更加灵活和强大。
希望这个简单的例子能帮助你理解Python的魔法方法!
代码示例
class Book:
def __init__(
self,
title,
author,
pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return (
f"Title:"
f"{self.title},"
f"Author:"
f"{self.author}")
def __len__(self):
return self.pages
def __add__(self, other):
return (
self.pages
+ other.pages)
book1 = Book(
"The Lord"
"of the Rings",
"J.R.R."
"Tolkien",
1178)
book2 = Book(
"Pride and"
"Prejudice",
"Jane Austen",
432)
print(book1)
print(len(book1))
print(book1 + book2)