24. 魔术方法

69 阅读1分钟

之前在介绍类的定义的时候有介绍了魔术方法,这小节再详细地介绍一下

一,基本概念

魔术方法就是以两个下划线开头且以两个下划线结尾的方法。又称特殊方法

特点:在特定情况下,会被自动调用,不需要我们手动调用

二,常见魔术方法

1,init(self[,...])

前面有讲,就是一个初始化方法,在实例化的过程中调用

class Student:
    def __init__(self, name, age, weight): 
        self.name = name
        self.age = age self.weight = weight

stu1 = Student('zhangsan', 14, 8) 
stu2 = Student('jige', 15, 6) 

2, call(self[,...])

当实例对象像函数那样调用,会调用该方法

class Student:
    def __call__(self): 
        print('好好好这么玩是吧')

stu1 = Student() 
stu1()

3,getitem(self, key)

执行self[key]时,会调用该方法,会返回所给key对应的值

class Student:
    def __getitem__(self, key): 
        print(['a', 'b', 'c'][key])

stu1 = Student() 
stu1[1]

输出为

b

4, len(self)

对实例对象求长度时,会调用该方法,必须返回整数类型

class Student:
    def __len__(self): 
        return 1

stu1 = Student() 
print(len(stu1))

输出为

1

5,str(self)

类似于__len__,实例对象转字符串的时候会调用该方法,只是返回值需要为字符串类型