凡是在类内部定义,以__ 开头__ 结尾的方法都是类的的内置方法,也称为魔法方法python
类的内置方法,会在某种条件知足下自动触发code
在调用类时自动触发对象
在 __ init __ 触发前自动触发,调用该类是,内部会经过__ new __ 产生一个新的对象递归
class Demo: # 在__init__触发前自动触发 def __new__(cls, *args, **kwargs): print('__new__执行') # 内部会经过object产生一个新对象返回来触发__init__,若是此处未返回新对象,则不会触发__init__ return object.__new__(cls, *args, **kwargs) def __init__(self): print('__init__执行') obj = Demo() # __new__执行 # __init__执行
在经过 “ 对象 . 属性 ” 获取对象属性时,若没有该属性时触发字符串
class Demo: # 在经过 “ 对象.属性 ” 获取对象属性时,若没有该属性时触发 def __getattr__(self, item): print('__getattr__执行') print(item) # 没有时默认返回None,能够设置默认返回值 return '设置的默认返回值' obj = Demo() print(obj.x) # __getattr__执行 # x # 设置的默认返回值
在经过 “ 对象.属性 ” 获取对象属性时,无论没有该属性,都会触发get
**注意:当 __ getattr __ 和 __ getattribute __ 同时存在在类内部时,只会触发 __ getattribute __ **it
class Demo: def __getattribute__(self, item): print('__getattribute__执行') print(item) # 无论有没有都是默认返回None,能够设置默认返回值 return '设置的默认返回值' # 此处没法获取查找的属性值,不能经过对象.属性来查找属性值不然会形成递归致使程序崩溃 # return self.__dict__[item] # return getattr(self, item) obj = Demo() obj.x = 10 print(obj.x) # __getattribute__执行 # x # 设置的默认返回值
当使用 “ 对象 . 属性 = 属性值” 时,添加或修改属性值时触发class
class Demo: # 当使用 对象. 属性 = 属性值 时触发 def __setattr__(self, key, value): print('__setattr__执行') print(key,value) #须要将添加或修改的属性加到对象名称空间中 self.__dict__[key] = value obj = Demo() print(obj.__dict__) # {} obj.x = 10 # __setattr__执行/ x 10 print(obj.__dict__) # {'x': 10}
在调用对象,“ 对象()”时触发object
class Demo: # 使用对象()调用对象时触发 def __call__(self, *args, **kwargs): print('__call__执行') # 默认返回None,能够设置默认返回值 return '设置默认值' obj = Demo() print(obj()) # __call__执行 # 设置默认值
在打印对象时触发,必要要有一个 “ 字符串 ” 返回值程序
class Demo: def __str__(self): print('__str__执行') # 必需要有一个字符串返回值 return '字符串' obj = Demo() print(obj) # __str__执行 # 字符串
在经过“ 对象[key]” 来获取属性值时触发
class Demo: def __getitem__(self, item): print('__getitem__执行') print(item) # 查找到value的值并返回,没有会报错,不写此步无论有没有都会返回None return self.__dict__[item] obj = Demo() obj.x = 10 print(obj['x']) # __getitem__执行 # x # 10
在经过 “ 对象[key] = value ”设置属性时触发
class Demo: def __setitem__(self, key, value): print('__getitem__执行') print(key, value) # 须要将添加或修改的属性加到对象名称空间中 self.__dict__[key] = value obj = Demo() print(obj.__dict__) #{} obj['x'] = 10 # __getitem__执行 # x 10 print(obj.__dict__) # {'x': 10}