魔法方法

发布时间 2024-01-08 21:11:46作者: -半城烟雨

魔法方法

__init__	:初始化类时触发
__del__		:删除类时触发
__new__		:构造类时触发
__str__		:str函数或者print函数触发
__repr__	:repr或者交互式解释器触发
__doc__		:打印类内的注释内容
__enter__	:打开文档触发
__exit__	:关闭文档触发
__getattr__ : 访问不存在的属性时调用
__setattr__ :设置实例对象的一个新的属性时调用
__delattr__ :删除一个实例对象的属性时调用
__setitem__	:列表添加值
__getitem__ :将对象当作list使用 
__delitem__	:列表删除值
__call__	:对象后面加括号,触发执行
__iter__	:迭代器

【一】__init__(),__str__()__,__getattr__()

class People(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        print('打印的时候触发了')
        return f'当前是{self.name},年龄是{self.age}'
    #访问不存在的属性 p.hobby时调用
    def __getattr__(self, item):
        print('调用了getattr')
        return f'没有{item}这个属性'
    #先于__getattr__触发
    def __getattribute__(self, item):
        print('调用了getattribute')
        if hasattr(self,item):
            return self.item
        else:
            raise ValueError(f"当前键{item}不存在")      
     def __delattr__(self, item):
        print(item)
        print(f'删除触发')
        #拦截某个敏感数据
        if item=='hobby':
            raise Exception(f'不能删除{item}')     
      #__call__ 方法 : 当想把对象当函数代用的时候可以给我们的类加一个 __call__ 方法,让他能被调用
     def __call__(self, *args, **kwargs):
        print(args)
        print(kwargs)
        print(f'对象() 会触发我! ')       
p=People('张三',20)
print(p)
print(p.name)
print(p.hobby)
del p.age

【二】__getattr__方法

class People(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
    #访问不存在的属性 p.hobby时调用
    def __getattr__(self, item):
        print('调用了getattr')
        return f'没有{item}这个属性'
    
p=People('张三',20)
print(p.hobby) 
#没有hobby这个属性
    

【三】__call__方法

class People(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
     def __call__(self, *args, **kwargs):
        print(args)
        print(kwargs)
        print(f'对象() 会触发我! ')  
p=People('张三',20)
p(name='asd')
#()
#{'name': 'asd'}
对象() 会触发我!        

【四】__setattr___delattr____getattr__方法

 #设置键会触发
def __setattr__(self, key, value):
        ...
 # 删除键会触发
def __delattr__(self, item):  
    ...
# __getattr__ : 没有键才会触发
def __getattr__(self, item):
    ...

__enter____exit__方法

class Mywith(object):
    def __enter__(self):
        fp=open('01.txt','w',encoding='utf-8')
        print('进入__enter__ 触发')
        return fp
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('退出__exit__ 触发')
        fp.close()

with Mywith() as fp:
    fp.write('hello world')
    print('写入完成')
#进入__enter__ 触发
#写入完成
#退出__exit__ 触发