Python常用魔术方法汇总(20个魔法函数)

发布时间 2023-09-18 21:18:38作者: 勾影变形计

本文将为您详细介绍Python中的让我们一起来了解这些特殊的函数,并提供一些在实际接口自动化工作中的示例代码。魔法函数(Magic Methods),也被称为特殊方法或双下划线方法,是Python中一些特殊命名的函数,它们以双下划线开头和结尾。这些函数定义了对象在特定情况下的行为,例如创建、比较、运算、迭代等。

 

Python魔法函数的作用

1、Python魔法函数主要是为某些特殊需求而设计的。例如__str__()和__repr__()函数用于打印输出对象的信息,__add__()函数用于定义两个对象相加的行为,__len__()函数定义当被len()调用时的行为等。

2、在Python中,大量使用魔法函数可以提高代码的可读性和可维护性,使开发更加方便快捷。

(Python魔法函数是实现Python语法糖的一种方式,可以更加方便快捷地编写代码,提高代码的可读性和可维护性。)

 

以下是20个常用的魔法函数及其功能的详细解释和示例代码:


__init__(self[, args...]):对象初始化函数,在创建对象时调用。

class MyClass:
    def __init__(self, name):
        self.name = name
obj = MyClass("Alice")

 

__str__(self):返回对象的字符串表示。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return f"({self.x}, {self.y})"
p = Point(3, 4)
print(p)  # 输出: (3, 4)

 

__len__(self):返回对象的长度。

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

 

__getitem__(self, key):获取对象的指定元素。

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

 

__setitem__(self, key, value):设置对象的指定元素。

class MyList:
    def __init__(self, items):
        self.items = items
    def __setitem__(self, index, value):
        self.items[index] = value
my_list = MyList([1, 2, 3, 4, 5])
my_list[2] = 10
print(my_list.items)  # 输出: [1, 2, 10, 4, 5]

 

__delitem__(self, key):删除对象的指定元素。

class MyList:
    def __init__(self, items):
        self.items = items
    def __delitem__(self, index):
        del self.items[index]
my_list = MyList([1, 2, 3, 4, 5])
del my_list[2]
print(my_list.items)  # 输出: [1, 2, 4, 5]

 

__contains__(self, item):判断对象是否包含指定元素。

class MyList:
    def __init__(self, items):
        self.items = items
    def __contains__(self, item):
        return item in self.items
my_list = MyList([1, 2, 3, 4, 5])
print(3 in my_list)  # 输出: True

 

__iter__(self):返回迭代器对象。

class MyList:
    def __init__(self, items):
        self.items = items
    def __iter__(self):
        return iter(self.items)
my_list = MyList([1, 2, 3, 4, 5])
for item in my_list:
    print(item)  # 依次输出: 1, 2, 3, 4, 5

 

__next__(self):返回迭代器的下一个元素。

class MyList:
    def __init__(self, items):
        self.items = items
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        if self.index >= len(self.items):
            raise StopIteration
        value = self.items[self.index]
        self.index += 1
        return value
my_list = MyList([1, 2, 3, 4, 5])
for item in my_list:
    print(item)  # 依次输出: 1, 2, 3, 4, 5

 

__eq__(self, other):判断两个对象是否相等。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
p1 = Point(3, 4)
p2 = Point(3, 4)
print(p1 == p2)  # 输出: True

 

__lt__(self, other):判断一个对象是否小于另一个对象。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __lt__(self, other):
        return self.x < other.x and self.y < other.y
p1 = Point(2, 3)
p2 = Point(3, 4)
print(p1 < p2)  # 输出: True

 

__gt__(self, other):判断一个对象是否大于另一个对象。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __gt__(self, other):
        return self.x > other.x and self.y > other.y
p1 = Point(3, 4)
p2 = Point(2, 3)
print(p1 > p2)  # 输出: True

 

__add__(self, other):定义对象的加法操作。

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)
result = v1 + v2
print(f"({result.x}, {result.y})")  # 输出: (4, 6)

 

__sub__(self, other):定义对象的减法操作。

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(3, 4)
v2 = Vector(1, 2)
result = v1 - v2
print(f"({result.x}, {result.y})")  # 输出: (2, 2)

 

__mul__(self, other):定义对象的乘法操作。

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __mul__(self, factor):
        return Point(self.x * factor, self.y * factor)
p = Point(2, 3)
result = p * 2
print(f"({result.x}, {result.y})")  # 输出: (4, 6)

 

__call__(self[, args...]):使对象可调用。

class Calculator:
    def __call__(self, a, b):
        return a + b
calc = Calculator()
result = calc(3, 4)
print(result)  # 输出: 7

 

__enter__(self) 和 __exit__(self, exc_type, exc_value, traceback):定义上下文管理器。

class FileManager:
    def __init__(self, filename):
        self.filename = filename
    def __enter__(self):
        self.file = open(self.filename, 'r')
        return self.file
    def __exit__(self, exc_type, exc_value, traceback):
        self.file.close()
with FileManager("example.txt") as file:
    contents = file.read()
    print(contents)

 

__getattr__(self, name):在访问不存在的属性时调用。

class Person:
    def __getattr__(self, name):
        return f"Attribute '{name}' does not exist."
p = Person()
print(p.age)  # 输出: Attribute 'age' does not exist.


__setattr__(self, name, value):在设置属性值时调用。
class Person:
    def __setattr__(self, name, value):
        print(f"Setting attribute '{name}' to '{value}'")
        super().__setattr__(name, value)
p = Person()
p.name = "Alice"  # 输出: Setting attribute 'name' to 'Alice'

 

__delattr__(self, name):在删除属性时调用。

class Person:
    def __delattr__(self, name):
        print(f"Deleting attribute '{name}'")
        super().__delattr__(name)
p = Person()
del p.name  # 输出: Deleting attribute 'name'