当前位置: 首页 > article >正文

Python 魔术方法

在Python中,魔术方法(Magic Methods)或称为双下划线方法(Dunder Methods),是一类具有特殊用途的方法,其名称前后都带有两个下划线(如 __init____str__ 等)。这些方法定义了对象的内置行为,使得类的实例能够表现得像内置类型一样。以下是Python中一些常用的魔术方法及其使用示例:

1. __init__(self, ...)

用于对象的初始化。在创建对象时调用。

 

python复制代码

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Alice", 30)
print(p.name, p.age) # 输出: Alice 30

2. __str__(self)

定义对象的字符串表示。当使用 print() 或 str() 函数时调用。

 

python复制代码

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
p = Person("Alice", 30)
print(p) # 输出: Person(name=Alice, age=30)

3. __repr__(self)

定义对象的“官方”字符串表示,通常用于调试。repr() 函数会调用这个方法。

 

python复制代码

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
p = Person("Alice", 30)
print(repr(p)) # 输出: Person(name='Alice', age=30)

4. __add__(self, other)

定义加法运算符(+)的行为。

 

python复制代码

class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3.x, v3.y) # 输出: 4 6

5. __getitem__(self, key)

定义获取元素的行为,用于索引操作(如 obj[key])。

 

python复制代码

class MyList:
def __init__(self, elements):
self.elements = elements
def __getitem__(self, key):
return self.elements[key]
ml = MyList([1, 2, 3, 4, 5])
print(ml[1]) # 输出: 2

6. __setitem__(self, key, value)

定义设置元素的行为,用于索引赋值操作(如 obj[key] = value)。

 

python复制代码

class MyList:
def __init__(self, elements):
self.elements = elements
def __getitem__(self, key):
return self.elements[key]
def __setitem__(self, key, value):
self.elements[key] = value
ml = MyList([1, 2, 3, 4, 5])
ml[1] = 10
print(ml[1]) # 输出: 10

7. __len__(self)

定义获取对象长度(如列表长度)的行为,用于 len() 函数。

 

python复制代码

class MyList:
def __init__(self, elements):
self.elements = elements
def __len__(self):
return len(self.elements)
ml = MyList([1, 2, 3, 4, 5])
print(len(ml)) # 输出: 5

8. __call__(self, *args, **kwargs)

定义对象像函数一样被调用的行为(如 obj())。

 

python复制代码

class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return x + self.n
add_five = Adder(5)
print(add_five(3)) # 输出: 8

9. __enter__(self) 和 __exit__(self, exc_type, exc_val, exc_tb)

用于定义对象的上下文管理行为,通常与 with 语句一起使用。

 

python复制代码

class MyContext:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting the context")
return False # 如果返回 True,则异常会被忽略
with MyContext() as ctx:
print("Inside the context")
# 输出:
# Entering the context
# Inside the context
# Exiting the context

这些魔术方法是Python面向对象编程中非常强大的一部分,通过它们可以使自定义的类表现得更加自然和符合直觉。


http://www.kler.cn/news/356839.html

相关文章:

  • rpc的客户端为什么称为stub
  • 人工智能学习框架的探索与应用:从基础到前沿
  • scrapy 爬虫学习之【中医药材】爬虫
  • 【Hive】2-Apache Hive概述、架构、组件、数据模型
  • URP学习三
  • 使用 NVBit 进行内存访问跟踪指南
  • Java知识巩固(四)
  • SpringBoot车辆管理系统:构建与优化
  • 遍历一个list,并删除集合中元素的几种方式
  • 【Linux网络编程】Socket编程--UDP(第一弹):实现客户端和服务器互相发送消息
  • 【数据结构】栈的创建
  • Redis --- 第六讲 --- 关于持久化
  • nodejs使用redis工具类示例
  • YoloV9改进策略:主干网络改进|DeBiFormer,可变形双级路由注意力|全网首发
  • stm32通过串口读取JY61 JY62数据(HAL库)
  • URP学习(一)
  • 机器学习核心功能:分类、回归、聚类与降维
  • AJAX——POST 设置请求体参数
  • IP基本原理
  • 【nlp】知识蒸馏Distilling