类的内置方法(魔法方法)

类的内置方法(魔法方法)

凡是在类内部定义,以__ 开头__ 结尾的方法都是类的的内置方法,也称为魔法方法

类的内置方法,会在某种条件满足下自动触发

1、__ init__

在调用类时自动触发

2、__ new__

在 __ 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__执行 

3、__ getattr__

在通过 “ 对象 . 属性 ” 获取对象属性时,若没有该属性时触发

class Demo:
    # 在通过 “ 对象.属性 ” 获取对象属性时,若没有该属性时触发
    def __getattr__(self, item):
        print('__getattr__执行')
        print(item)
        # 没有时默认返回None,可以设置默认返回值
        return '设置的默认返回值'

obj = Demo()
print(obj.x)
# __getattr__执行
# x
# 设置的默认返回值

  

4、__ getattribute__

在通过 “ 对象.属性 ” 获取对象属性时,不管没有该属性,都会触发

注意:当 __ getattr __ 和 __ getattribute __ 同时存在在类内部时,只会触发 __ getattribute __

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
# 设置的默认返回值

5、__ setattr __

当使用 “ 对象 . 属性 = 属性值” 时,添加或修改属性值时触发

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}  

6、__ call__

在调用对象,“ 对象()”时触发

class Demo:
    # 使用对象()调用对象时触发
    def __call__(self, *args, **kwargs):
        print('__call__执行')
        # 默认返回None,可以设置默认返回值
        return '设置默认值'

obj = Demo()
print(obj())
# __call__执行
# 设置默认值

7、__ str__

在打印对象时触发,必要要有一个 “ 字符串 ” 返回值

class Demo:
    def __str__(self):
        print('__str__执行')
        # 必须要有一个字符串返回值
        return '字符串'

obj = Demo()
print(obj)
# __str__执行
# 字符串 

8、__ getitem__

在通过“ 对象[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  

9、__ setitem__

在通过 “ 对象[key] = value ”设置属性时触发

class Demo:
    def __setitem__(self, key, value):
        print('__setitem__方法执行')
        print(key, value)
        # 需要将添加或修改的属性加到对象名称空间中
        self.__dict__[key] = value

obj = Demo()
print(obj.__dict__)  #{}
obj['x'] = 10
# __getitem__执行
# x 10
print(obj.__dict__) # {'x': 10}

  

 

 

原文地址:https://www.cnblogs.com/lvguchujiu/p/11959946.html