Python-魔法函数(学习笔记2)

概述

本文由四部分组成:

什么是魔法函数

python的数据模型以及数据模型对python的影响

魔法函数一览

魔法函数的重要性(len函数)

什么是魔法函数

Python内置的以双下划线开头 并以双下划线结尾的函数(不能自己定义,没有用),如__init__(),str(),__getitem()__等很多,用于实现并定制很多特性,非常灵活,且是隐式调用的。

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list


company = Company(['tom', 'bob', 'jane'])

emploee = company.employee
for em in emploee:
    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)

两个例子输出结果都是:

tom
bob
jane

注:getitem()可以把类变成一个可迭代的对象(一次一次取数据,直到抛异常)

python的数据模型以及数据模型对python的影响

魔法函数会影响到Python语法本身,如让类变成可迭代的对象,也会影响Python的一些内置函数的调用,如实现__len__()能对对象调用len()方法。

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list

    def __len__(self):
        return len(self.employee)


company = Company(['tom', 'bob', 'jane'])


print(len(company))			#输出结果为:3

上例子中如注释掉以下__len__函数则报错,

 def __len__(self):
        return len(self.employee)

魔法函数一览

__str__与__repr__
魔法函数

魔法函数的重要性(len函数)

len函数的特殊性
使用python的内置函数 性能高
如果len()方法调用的对象是Python内置的类型,为了提高效率而走捷径,如list,set,dict(cpython)等,会直接获取(有一个数据表示长度),而不用去遍历。

发布了29 篇原创文章 · 获赞 19 · 访问量 1325

猜你喜欢

转载自blog.csdn.net/s1156605343/article/details/104284090