12个Python开发者必知必会的魔术方法

e91725d78323f52546bffc2aa729d216.jpeg

更多Python学习内容:ipengtao.com

Python中的魔术方法(Magic Methods)是一组特殊的方法,它们以双下划线开头和结尾,例如__init____str__。这些方法可以定义自定义类的行为,使对象可以与Python的内置功能(例如lenstr+等)协作。本文将介绍12个Python开发者必知必会的魔术方法,以及如何使用它们来定制类。

1. __init__

__init__方法是类的构造方法,在创建类的实例时自动调用。它用于初始化对象的属性。

class MyClass:
    def __init__(self, value):
        self.value = value

obj = MyClass(42)
print(obj.value)  # 输出 42

2. __str__

__str__方法用于返回对象的字符串表示。当调用str(obj)时,它将调用对象的__str__方法。

class MyClass:
    def __init__(self, value):
        self.value = value
    
    def __str__(self):
        return f"MyClass with value {self.value}"

obj = MyClass(42)
print(str(obj))  # 输出 "MyClass with value 42"

3. __repr__

__repr__方法用于返回对象的“官方”字符串表示,通常是一个可以用来重新创建对象的表达式。当在交互式环境中直接输入对象名时,它将调用对象的__repr__方法。

class MyClass:
    def __init__(self, value):
        self.value = value
    
    def __repr__(self):
        return f"MyClass({self.value})"

obj = MyClass(42)
print(obj)  # 输出 "MyClass(42)"

4. __len__

__len__方法用于返回对象的长度,通常与内置函数len一起使用。

class MyList:
    def __init__(self, data):
        self.data = data
    
    def __len__(self):
        return len(self.data)

my_list = MyList([1, 2, 3, 4, 5])
print(len(my_list))  # 输出 5

5. __getitem____setitem__

__getitem__方法用于获取对象的元素,__setitem__方法用于设置对象的元素。这使得类可以像列表或字典一样操作。

class MyList:
    def __init__(self, data):
        self.data = data
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __setitem__(self, index, value):
        self.data[index] = value

my_list = MyList([1, 2, 3, 4, 5])
print(my_list[2])  # 输出 3
my_list[2] = 42
print(my_list[2])  # 输出 42

6. __iter____next__

__iter__方法返回一个可迭代对象,__next__方法用于获取下一个元素。这使得类可以支持迭代。

class MyRange:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current < self.limit:
            result = self.current
            self.current += 1
            return result
        else:
            raise StopIteration

my_range = MyRange(5)
for num in my_range:
    print(num)  # 输出 0 1 2 3 4

7. __contains__

__contains__方法用于检查对象是否包含某个值。它通常与in操作符一起使用。

class MyList:
    def __init__(self, data):
        self.data = data
    
    def __contains__(self, item):
        return item in self.data

my_list = MyList([1, 2, 3, 4, 5])
print(3 in my_list)  # 输出 True

8. __eq__

__eq__方法用于定义对象之间的相等性。它通常与==操作符一起使用。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __eq__(self, other):
        if isinstance(other, Point):
            return self.x == other.x and self.y == other.y
        return False

p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)  # 输出 True

9. __lt__, __le__, __gt__, __ge__

这些方法分别用于定义对象之间的小于、小于或等于、大于和大于或等于关系。它们通常与比较操作符(例如<<=>>=)一起使用。

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def __lt__(self, other):
        return self.width * self.height < other.width * other.height
    
    def __le__(self, other):
        return self.width * self.height <= other.width * other.height
    
    def __gt__(self, other):
        return self.width * self.height > other.width * other.height
    
    def __ge__(self, other):
        return self.width * self.height >= other.width * other.height

rect1 = Rectangle(3, 4)
rect2 = Rectangle(2, 6)
print(rect1 < rect2)   # 输出 True
print(rect1 <= rect2)  # 输出 True
print(rect1 > rect2)   # 输出 False
print(rect1 >= rect2)  # 输出 False

10. __add__

__add__方法用于定义对象之间的加法操作。它通常与+操作符一起使用。

class ComplexNumber:
    def __init__(self, real, imaginary):
        self.real = real
        self.imaginary = imaginary
    
    def __add__(self, other):
        return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)

c1 = ComplexNumber(1, 2)
c2 = ComplexNumber(2, 3)
result = c1 + c2
print(result.real, "+", result.imaginary, "i")  # 输出 3 + 5 i

11. __sub__

__sub__方法用于定义对象之间的减法操作。它通常与-操作符一起使用。

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

v1 = Vector(1, 2)
v2 = Vector(2, 3)
result = v1 - v2
print(result.x, result.y)  # 输出 -1 -1

12. __call__

__call__方法可以将对象作为函数调用。这意味着可以像函数一样调用对象,并在类中定义其行为。

class MyFunction:
    def __call__(self, *args):
        return sum(args)

add = MyFunction()
result = add(1, 2, 3, 4, 5)
print(result)  # 输出 15

结论

魔术方法是Python中非常强大和灵活的功能之一,它们可以自定义类的行为,使代码更具可读性和可维护性。本文介绍了12个常用的魔术方法,包括__init____str____repr____len____getitem____setitem____iter____next____contains____eq____lt__等等。通过熟练掌握这些魔术方法,可以更好地利用Python的强大功能,编写出更具表现力和功能性的自定义类。

如果你觉得文章还不错,请大家 点赞、分享、留言 下,因为这将是我持续输出更多优质文章的最强动力!

更多Python学习内容:ipengtao.com

干货笔记整理

  100个爬虫常见问题.pdf ,太全了!

Python 自动化运维 100个常见问题.pdf

Python Web 开发常见的100个问题.pdf

124个Python案例,完整源代码!

PYTHON 3.10中文版官方文档

耗时三个月整理的《Python之路2.0.pdf》开放下载

最经典的编程教材《Think Python》开源中文版.PDF下载

9bfcb6c3dd29dfa76911a6820262b83c.png

点击“阅读原文”,获取更多学习内容

相关推荐

  1. 10SQL聚合函数

    2024-01-01 12:34:04       17 阅读
  2. Linux中mount命令

    2024-01-01 12:34:04       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-01 12:34:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-01 12:34:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-01 12:34:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-01 12:34:04       20 阅读

热门阅读

  1. 2024-01-01 事业-代号s-营销的16个关键词

    2024-01-01 12:34:04       29 阅读
  2. reactAPI讲解以及注意事项

    2024-01-01 12:34:04       39 阅读
  3. 698. 划分为k个相等的子集(中等)

    2024-01-01 12:34:04       36 阅读
  4. 批量估计问题

    2024-01-01 12:34:04       35 阅读
  5. 微信小程序有几个文件

    2024-01-01 12:34:04       34 阅读
  6. 123456

    2024-01-01 12:34:04       36 阅读
  7. 帕金森病的病因是什么?

    2024-01-01 12:34:04       34 阅读
  8. [react]react-router-dom 与 redux 版本升级

    2024-01-01 12:34:04       37 阅读
  9. MATLAB常用笔记记录(持续更新)

    2024-01-01 12:34:04       57 阅读
  10. Python基础中的列表知识整理归纳

    2024-01-01 12:34:04       37 阅读