认识python中的魔法函数:
认识魔法函数的作用
魔法函数:
1、 以双下划线开头双下划线结尾,比如 def __init __()
2、 魔法函数是python自己提供的
1.def __ init __(self)魔法函数:
1、 实例函数
2、实例对象调用
如下代码animals是init函数下的属性,所以要用实例对象来调用,用类对象无法调用。
class Zoo():
def __init__(self,animal_list):
self.animals = animal_list
zoo = Zoo(["tiger",'lion','monkey','snake'])
animal_list = zoo.animals
for animal in animal_list:
print(animal)
---------------------------------------------
tiger
lion
monkey
snake
1.def __getitem__(self, item)魔法函数:
1.def __getitem__(self, item) 函数 item是位置参数,自动遍历至抛异常为止。
2.实例化对象是自动加载,当用for循环调用实例时python解释器会自动调用该魔法函数。
class Zoo():
def __init__(self,animal_list):
self.animals = animal_list
def __getitem__(self, item):
return self.animals[item]
zoo = Zoo(["tiger",'lion','monkey','snake'])
for animal in zoo:
print(animal)
---------------------------------------
tiger
lion
monkey
snake
1、 当对象被执行遍历操作时,会先去找对象中有没有iter的魔法函数,没有的话再去找getitem函数