python中一切皆对象
魔法函数是在类中以双下划线开头,双下划线结尾的,python本身给我们定义了许多这种方法,让我们能在类中直接使用。
比如我们要遍历一个类中的列表,我们普通的做法如下
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
company = Company(['tom', 'bob', 'jane'])
employee = company.employee
for em in employee :
print(em)
但如果我们使用魔法函数,就变成了
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __getitem__(self, item):
return self.employee[item]
company = Company(['tom', 'bob', 'jane'])
for em in company:
print(em)
实例化一个类之后就可以直接遍历
用魔法函数,让列表输出时变成字符串,__str__这个函数会在被打印时自动调用
class Company(object):
def __init__(self, employee_list):
self.employee = employee_list
def __str__(self):
return ','.join(self.employee)
company = Company(['tom', 'bob', 'jane'])
print(company)
__add__的用法,在使用+的使用自动调用该方法
class MyVector(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other_instance):
re_vector = MyVector(self.x + other_instance.x, self.y + other_instance.y)
return re_vector
def __str__(self):
return "x:{x},y:{y}".format(x=self.x, y=self.y)
first_vec = MyVector(1, 2)
second_vec = MyVector(2, 3)
print(first_vec + second_vec)
当我们使用len函数时,其实会调用魔法函数__len__,而且我们在遍历set,list,dict这些python内置的数据结构,它不会每次都去遍历,这样效率低,它会去维护一个数来保存他们的数量,因为这些内置的数据类型是用cpython解释器写的,底层是c语言,效率很高。