首页 > 编程语言 >Python 20个魔法函数

Python 20个魔法函数

时间:2023-07-15 16:35:28浏览次数:31  
标签:__ 20 Python items self 魔法 other class def

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

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



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

class MyClass:    def __init__(self, name):        self.name = nameobj = 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] = valuemy_list = MyList([1, 2, 3, 4, 5])my_list[2] = 10print(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.itemsmy_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 valuemy_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.yp1 = 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.yp1 = 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.yp1 = 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 + v2print(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 - v2print(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 * 2print(f"({result.x}, {result.y})")  # 输出: (4, 6)

 

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

class Calculator:    def __call__(self, a, b):        return a + bcalc = 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'

 

 

标签:__,20,Python,items,self,魔法,other,class,def
From: https://www.cnblogs.com/QQ-77Ly/p/17556311.html

相关文章

  • Python学习——Day 6
    流程控制语句break·break语句   ·用于结束循环结构,通常与分支结构if一起使用#输入密码,最多录入3次,如果正确就结束循环foriteminrange(3):pwd=input('请输入密码:')ifpwd=='8888':print('密码正确')breakelse:print('密码......
  • Anaconda-用conda创建python虚拟环境及移植到内网
    conda可以理解为一个工具,也是一个可执行命令,其核心功能是包管理和环境管理。包管理与pip的使用方法类似,环境管理则是允许用户方便滴安装不同版本的python环境并在不同环境之间快速地切换。conda的设计理念conda将几乎所有的工具、第三方包都当作package进行管理,甚至包括python......
  • python aes
    实现PythonAES加密解密背景AES(AdvancedEncryptionStandard)是一种对称密钥加密算法,广泛应用于数据的加密和解密过程中。在Python中,我们可以使用cryptography模块来实现AES加密解密功能。整体流程下面是实现PythonAES加密解密的整体流程:步骤描述1.导入......
  • python __init__传参
    Python__init__传参在Python的类定义中,__init__是一个特殊的方法,它用于在创建类的实例时进行初始化操作。通过在__init__方法中传递参数,我们可以在创建实例时为对象提供初始值。本文将详细介绍Python中__init__方法的使用和传参方式,并提供一些示例代码帮助读者更好地理解。__ini......
  • python \x00\x00\ 转换
    Python字符串转换为\x00\x00\x00格式的实现方法1.简介在Python中,字符串可以使用不同的编码方式进行表示。其中,\x00\x00\x00是一种十六进制表示的编码方式,代表了字符串中的空字符。本文将介绍如何将普通的Python字符串转换为\x00\x00\x00格式。2.转换流程下表展示了将Pytho......
  • python WM_MOUSEWHEEL
    实现"pythonWM_MOUSEWHEEL"的步骤1.了解WM_MOUSEWHEEL消息WM_MOUSEWHEEL是Windows消息之一,用于处理鼠标滚轮相关的操作。在Python中,我们可以使用win32api和win32con库来发送和处理Windows消息。2.安装所需库在开始编写代码之前,你需要安装pywin32库来操作Windows消息。可以使......
  • python ValueError: No JSON object could be decoded
    解决“pythonValueError:NoJSONobjectcouldbedecoded”问题概述在Python开发中,我们经常会遇到处理JSON数据的情况。然而,在处理JSON数据时,有时会遇到ValueError:NoJSONobjectcouldbedecoded的错误。这个错误通常发生在尝试将字符串解析为JSON对象时,但字符串无效或无......
  • python TensorFlow保存模型
    TensorFlow保存模型作为经验丰富的开发者,我将指导你如何在Python中使用TensorFlow保存模型。在本文中,我将通过表格展示整个流程,并为每一步提供所需的代码和注释。流程下面是保存TensorFlow模型的整个流程:步骤描述1导入必要的库2创建模型3训练模型4保存模......
  • python Tensor 转string
    PythonTensor转string实现介绍在机器学习和深度学习中,Tensor(张量)是一个非常常见的数据结构,它是一个多维数组,用于存储和处理大规模的数据。在某些情况下,我们可能需要将一个Tensor转换为字符串,以便于输出、存储或传输。本文将向你展示如何使用Python实现这个功能。实现步骤下......
  • python STM32
    如何在Python中使用STM32前言欢迎来到PythonSTM32入门教程!在本篇文章中,我将向你介绍如何在Python中使用STM32。STM32是一种基于ARMCortex-M内核的32位微控制器,具有广泛的应用领域,包括物联网、嵌入式系统和工业自动化等。通过本教程,你将学会如何在Python中编写STM32程序,并将其烧......