Python Foundation: double bottom method

Posted by jfgreco915 on Mon, 20 Apr 2020 17:27:10 +0200

1. Double down method

Definition: double down method is a special method, which is provided by the interpreter and has special significance. Double down method is mainly used by python source code programmers. We try not to use double down method in development, but it is a deep study of double down method, which is more beneficial for us to read source code.

(1) Call: different double methods have different triggering methods,

<1> Len -- len() triggered

class A(object):

    def __init__(self,name):
        self.name = name
        print("Triggered__init__")

    def __len__(self):     # len() trigger
        print("Come here")
        return len(self.name)    # Return len ("xqrqwr") str__
        # There must be a return value, and the type of the return value must be integer

a = A("xqrqwr")
print(len(a))

# str
a = "12345"      # An instance of str
lst = [1,2,3,4,4,5,5,5,5] # list is an instance of this class
print(len(a))
print(len(lst))

<2> Triggered by -- hash()

class A(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __hash__(self):  # hash()
        hash({1,2,345})  # Variable data class, non data type
        return 1
        # There must be a return value, and the type of the return value must be integer

a = A("meet",25)
print(hash(a))

<3> STR -- print or str() trigger

class A:

    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

    def __str__(self):   # print triggers str()
        print(111)
        return f"Full name:{self.name} Age:{self.age} Gender:{self.sex}"
        # There must be a return value of type string


a = A("mee",20,"male")
a1 = A("mee1",200,"Man 1")
str(a)
print(a)
print(a1)


# The following comparison:
a = A("mee",20,"male")
a1 = A("mee2",200,"female")

print(f"Full name:{a.name} Age:{a.age} Gender:{a.sex}")   # "Name: meet age: 20 gender: male"
print(f"Full name:{a1.name} Age:{a1.age} Gender:{a1.sex}")  # "Name: meet2 age: 200 gender: female"

<4> "Repl" -- print or% r trigger

class A:

    def __init__(self):
        pass


    def __repr__(self):   # print trigger% r
        print(1111)
        return "Heaven devil"

    def __str__(self):   # STR priority is higher than repr. If both exist, only execute str
        return "Xiaoyuan"

a = A()
print("%r"%(a))

<5> Call call -- triggered when an object is called. The object is followed by parentheses, that is, object () or class () ()

class A:

    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):  # call called on object ()__
        print("Walk me")
        print(*args, **kwargs)

a = A()
a()

<6> Equal to

class A(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __eq__(self, other):     #  a == a1
        if self.name == other.name:
            return True
        else:
            return False

a = A("mee",56)
a1 = A("mee",108)

print(a == a1)

<7> Construction method, which automatically triggers execution when an object is released in memory

In general, this method does not need to be defined. Because python is a high-level language, programmers do not need to care about the allocation and release of memory when using it. Because the allocation and release of memory are all handed over to the python interpreter class for execution, so the call of destructor is automatically triggered by the interpreter when garbage collection.

class A:
    def __init__(self):
        pass

    def __del__(self):    del trigger
        print("Execute me on delete")

a = A()

import time
time.sleep(5)
del a

a = 1
b = a
a = b

Garbage collection mechanism:

    # 80  5/s
    # Reference count
    # Mark clear
    # Bag recycling bag 1: 10 2/h bag 2: 5/3 4h bag 3: 3 20h

<8> The "item" series can operate instance methods like Dictionaries

dic["key"] = value
del dic["key"]
dic["key"]
class A:

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __getitem__(self, item):
        print(self.__dict__)
        print(self.__dict__[item])  # What you get is a dictionary

    def __setitem__(self, key, value):
        self.__dict__[key] = value

    def __delitem__(self, key):
        del self.__dict__[key]

a = A("meet",58)
a["sex"] = "male"
a["sex"]
del a["sex"]
print(a.__dict__)

<9> Single mode (factory mode)

Singleton mode is a common software design mode. In its core structure, there is only one special class called singleton class. The single instance mode can ensure that there is only one instance of a class in the system and the instance is easy to be accessed by the outside world, so it is convenient to control the number of instances and save system resources. If you want to have only one object of a certain class in the system, the singleton pattern is the best solution.

class A(object):

    def __init__(self,name):  # initialization
        self.name = name
        print("I am__init__,Leave me first")

    def __new__(cls, *args, **kwargs):
        print("I am__new__,Leave me first")
        return "La La La"

a = A("meet")
print("Who am I?:",a)
'''
//No one answers the questions? Xiaobian created a Python learning exchange QQ group: 579817333 
//Looking for like-minded small partners, mutual help, there are good video learning tutorials and PDF ebooks in the group!
'''
class A(object):

    def __init__(self,name):  # initialization
        self.name = name
        print("I am__init__,Leave me first")

    def __new__(cls, *args, **kwargs):
        obj = object.__new__(A)
        print("Where am i?:",obj)
        return obj                   # obj == __init__()

a = A("meet")
print("Who am I?:",a)
class A(object):

    def __init__(self,name): # Rudimentary understanding
        self.name = name


    def __new__(cls, *args, **kwargs):
        obj = object.__new__(A)   # The call is "new" in the object class. Only "new" in the object class can create a space
        return obj   #essence: obj == __init__()     return __init__()  # Trigger the init method


a = A("mee")  # a is the memory address of the object
a1 = A("Heaven devil")  # a is the memory address of the object
a2 = A("Tianyang")  # a is the memory address of the object
print(a.name)
print(a1.name)
print(a2.name)
# Execute the new method first and then the init method
class A:
    __a = None  #__a =  0x000001F346079FD0

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __new__(cls, *args, **kwargs):
        if cls.__a is None:
            obj = object.__new__(cls)
            cls.__a = obj
        return cls.__a

a = A("mee",123)  # Address 0x000001F346079FD0
a1 = A("Heaven devil",11)
print(a.name)
print(a1.name)

Singleton mode: no matter how many times it is created, the same memory space is used

Module import, handwritten singleton mode

What happens when an object is instantiated:

Create the object and open up the object space__

Automatically execute the init method, implicitly passing the object address to self

Encapsulate object properties into object space

2. Context

(1)__ enter__

(2)__ exit__

class my_open:

    def __init__(self,file,mode="r",encoding="utf-8"):
        self.file = file
        self.mode = mode
        self.encoding = encoding

    def __enter__(self):
        self.f = open(self.file,self.mode,encoding=self.encoding)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_type,exc_val,exc_tb) # When there's no mistake, it's None
        self.f.close()


with my_open("a.txt") as ffff:
    for i in ffff:
        print(i)
print(ffff.read(1111))
print(ffff.read())

Topics: Python encoding