Chapter One Magic Function

Chapter One Magic Function

Common built-in types in python

What is a magic function?

 Python magic functions are always surrounded by double underscores, they can add special methods to your class. If your object implements one of these methods, then this method will be called under special circumstances, and you can define what you want

Behavior, and all of this happens automatically.

List of magic functions

Examples of magic functions

1.1.__getitem__

Turn the object into an iterable object

example:

class Company(object):
    def __init__(self,employee_list):
        self.employee = employee_list
    #Magic function, add iterable type to the class
    def __getitem__(self, item):
        return self.employee[item]

company = Company(['11','22','33'])

#Added the magic function "__getitem__", the class becomes iterable
for em in company:
    print(em) #11,22,33

If you don’t use the magic function to loop out the method of each employee

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


company = Company(['11','22','33'])

for em in company.employee:
    print(em)

You can also slice and get the length

class Company(object):
    def __init__(self,employee_list):
        self.employee = employee_list
    #Magic function
    def __getitem__(self, item):
        return self.employee[item]

company = Company(['11','22','33'])
#Can be sliced
company1 = company[:2]
#Can judge the length of len
print(len(company1)) #2

for em in company1:
    print(em) #11,22

1.2.__len__

class Company(object):
    def __init__(self, employee_list):
        self.employee = employee_list
    #
    # def __getitem__(self, item):
    # return self.employee[item]

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

company = Company(["11", "22", "33"])

#If the magic function is not added, len (company) will report an error
print(len(company)) #3

1.3. __repr__ and __str__

 1. Install interactive environment (jupyter)

pip install -i https://pypi.douban.com/simple ipython

pip install -i https://pypi.douban.com/simple notebook

#start up
ipython notebook

 2. Usage of __repr__ and __str__

Reference: https://cloud.tencent.com/developer/article/1139364 Chapter One Magic Function-Cloud + Community-Tencent Cloud