课程学习笔记参考https://coding.imooc.com/class/200.html(__bobby前辈所讲)
魔法函数,python 中以___开头,__结尾的函数。加入了__getitem__变得可迭代。
class School(object): def __init__(self, student_list): self.studet = student_list school1 = School(["a" , "b", "c"]) for item in school1.studet: print(item) class School_old(object): def __init__(self, student_list): self.studet = student_list def __getitem__(self, item): return self.studet[item] school2 = School_old(["a", "b", "c"]) for item in school2: print(item)>>>>>>>
a b c a b c
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
魔法函数
非数学运算 字符串表示(__repr__,__str__)__repr__和__str__这两个方法都是用于显示的,__str__是面向用户的,而__repr__面向程序员。,集合序列相关(__len__, __getitem__,__setitem__,__delitem__,__contains__,)迭代(__iter__,__next__,)可调用(__call__,)上下文管理器(__enter__,__exit__,)数值转换(__abs__,__bool__,__int__,__float__,__hash__,__index__),元类相关(__init__,__new__),属性相关(__getattr__,__setattr__, __getattribute__, __setattribute__,__dir__),属性描述符(__get__,__set__, __delete__),协程(__await__, __aiter__, __anext__, __aenter__, __aexit__)
数学运算 一元运算符(__neg__,__pos__,__abs__),二元运算符(__lt__,__le__,__eq__,__ne__,__gt__,__ge__),算术运算符(__add__,__sub__,__mul__, __mod__,__div__),反向算术运算符(__radd__,__rsub__,__rmul__),增量赋值算术运算符(__iadd__,__isub__,__imul__),位运算符(__invert__,__lshift__,__and__,__or__),反向位运算符(__rand__,__ror__),增量赋值位运算符(__irshift__, __ior__,__iand__)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------