4.魔法函数

魔法函数不需要调用,python解释器会自动调用魔法函数。

类的以双下划线开头和结尾的函数。

4.1非数学运算

4.1.1字符串表示

__repr__:面向程序员

__str__:面向用户

4.1.2集合、序列相关

__len__

__getitem__

__setitem__

__delitem__

__contains__

4.1.3迭代相关

__iter__

__next__

4.1.4可调用

__call__

4.1.5with上下文管理

__enter__

__exit__

class A():
    def __enter__(self):
        print("enter...")
        return self
    def f(self):
        print('f')
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit...')

with A() as a:
    a.f()
#enter...
#f
#exit...
import contextlib
@contextlib.contextmanager
def func1():
    print("enter...")
    yield {}
    print("exit...")

with func1() as func2:
    print("tt...")

4.1.6数值转换

__abs__

__bool__

__int__

__float__

__hash__

__index__

4.1.7元类相关

__new__

__init__

4.1.8属性相关

__getattr__、__setattr__

__getattribute__、__setattribute__

__dir__

4.1.9属性描述符

__get__

__set__

__delete__

4.1.10协程

__await__/__aiter__/anext__/__aenter__/aexit__

猜你喜欢

转载自blog.csdn.net/weixin_40744265/article/details/89027678