Python- magic function (study notes 2)

Outline

This article consists of four parts:

What is the magic function

Python impact of the data model and the data model of python

Magic Functions List

The importance of the function of magic (len function)

What is the magic function

Python built-in 以双下划线开头 并以双下划线结尾的函数(not their own definition, did not use), __ as __init (), str (), __ getItem () __ and many used to implement and customize many features, very flexible, and is implicitly called.

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)

Two output examples are:

tom
bob
jane

NOTE: getItem () can become a target class of one iteration (time and again fetching until Throws)

Python impact of the data model and the data model of python

Magic function will affect the Python syntax itself, as it makes the class can become a target of iterations, some calls will also affect the Python built-in functions, such as the realization __len __ () can call len () method on the object.

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

As commented on in the following examples are given __len__ function,

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

Magic Functions List

__str__ and __repr__
Magic function

The importance of the function of magic (len function)

len particularity function
使用python的内置函数 性能高
if the object len () method is called built-in type Python, 为了提高效率而走捷径as list, set, dict (cpython), etc., will be directly obtained (the length of a data representation), without having to traverse.

Published 29 original articles · won praise 19 · views 1325

Guess you like

Origin blog.csdn.net/s1156605343/article/details/104284090