02-魔法函数

一、魔法函数

1.1、什么是魔法函数

  魔法函数就是以双下划线开头,双下划线结尾。第二点就是必须使用Python提供给我们的魔法函数。魔法函数是与自定义的类有关的,目的是为了增强自定义类的特性。

class Students(object):
    def __init__(self,student_list): #初始化属性
        self.student = student_list

    def __getitem__(self, item):  #传入索引,从零开始,如果没有值了就停止运行。如果将此魔法方法注释掉会报错TypeError: 'Students' object is not iterable
        return self.student[item]   #增加此魔法方法给类增加了可迭代的属性


students = Students(["lishuntao","wang","li"])
for student in students:
    print(student,end=" ")    #lishuntao wang li 

1.2、Python的数据模型以及数据模型对Python的影响

  要成为一名高级的开发工程师,就需要对Python的内部源码做一定的理解,这样当自己定义类的时候,才会更加灵活的定义。例如下面这个例子:

class Students(object):
    def __init__(self,student_list):
        self.student = student_list

    def __getitem__(self, item):
        return self.student[item]

    def __len__(self):
        return len(self.student)  #这里一定要返回的是正整数


students = Students(["lishuntao","wang","li"])
print(len(students))  #当注释掉len魔法方法运行出现错误TypeError: object of type 'Students' has no len()
                    #当有len魔法函数的时候,运行出现值3

1.3、魔法函数一览

1.3.1、非数学运算

字符串表示:

__repr__  #在开发环境下调用,例如python解释器下,以及jupyter notebook下调用返回对象的地址(开发人员才用到的)
__str__   #对我们的对象进行字符串格式化的时候进行调用

集合序列相关:

__len__
__getitem__
__setitem__
__delitem__
__contains__

迭代相关:

__iter__
__next__

可调用:

__call__

with上下文管理器:

__enter__
__exit__

数值转换:

__abs__
__bool__
__int__
__float__
__hash__
__index__

元类相关:

__new__
__init__

属性相关:

__getattr____setattr__
__getattribute____setattribute__
__dir__

属性描述符:

__get____set____delete__

协程:

__await____aiter____anext____aenter____aexit__

1.3.2、数学运算

一元运算符:

__neg__(-)、__pos__(+)、__abs__

二元运算符:

__lt__(<)、__le__(<=)、__eq__(==)、__ne__(!=)、__gt__(>)、__ge__(>=)

算术运算符:

__add__(+)、__sub__(-)、__mul__(*)、__truediv__(/)、__floordiv(//)、__mod__(%)、__divmod__(divmod())、__pow__(**或pow())、__round__(round())

反向算数运算符:

__radd____rsub____rmul____rtruediv____rfloordiv__rmod____rdivmod____rpow__

增量赋值算数运算符:

__iadd____isub____imul____itruediv____ifloordiv__imod____ipow__

位运算符:

__invert__(~)、__lshift__(<<)、__rshift__(>>)、__and__(&)、__or__(|)、__xor__(^)

反向位运算符:

__rlshift____rrshift____rand____ror____rxor__

增量赋值算数运算符:

__ilshift____irshift____iand____ior____ixor__

1.4、魔法函数的重要性(len())

  在使用pythonlen函数的时候,尽量去使用python原生的类型(list、set、dict),这些类型性能很高.Cpython是用C语言写出来的,因此效率很高。再用python语法去写的话,效率会大大下降。因为魔法函数内部会做很多优化,大大提升效率。

猜你喜欢

转载自www.cnblogs.com/lishuntao/p/11962664.html
02-