Python Basics: Double Down Method

1. Double method

Definition: The double under method is a special method. It is a method with special meaning provided by the double underscore plus the method name plus the double underscore method name. The double under method is mainly used by Python source programmers. We try our best in development Don't use the double-down method, but in-depth study of the double-down method is more beneficial for us to read the source code.

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

<1> __ len__ – len () trigger

class A(object):

    def __init__(self,name):
        self.name = name
        print("触发了__init__")

    def __len__(self):     # len() 触发
        print("走这里")
        return len(self.name)    # return len("xqrqwr")  str中__len__
        # 必须有返回值,返回值的类型必须是整型

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

# str
a = "12345"      # str这个类的实例
lst = [1,2,3,4,4,5,5,5,5] # list这个类的实例
print(len(a))
print(len(lst))

<2> __ hash__ --hash () trigger

class A(object):

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

    def __hash__(self):  # hash()
        hash({1,2,345})  # 可变数据类,不可数据类型
        return 1
        # 必须有返回值,返回值的类型必须是整型

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

<3> __ str__ --print or str () trigger

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class A:

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

    def __str__(self):   # print 触发 str()
        print(111)
        return f"姓名:{self.name} 年龄:{self.age} 性别:{self.sex}"
        # 必须有返回值,返回值的类型必须是字符串


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


# 以下对比:
a = A("mee",20,"男")
a1 = A("mee2",200,"女")

print(f"姓名:{a.name} 年龄:{a.age} 性别:{a.sex}")   # "姓名:meet 年龄:20 性别:男"
print(f"姓名:{a1.name} 年龄:{a1.age} 性别:{a1.sex}")  # "姓名:meet2 年龄:200 性别:女"

<4> __ repr__ --print or% r trigger

class A:

    def __init__(self):
        pass


    def __repr__(self):   # print触发  %r
        print(1111)
        return "天魔"

    def __str__(self):   # str 优先级高于 repr  两个都存在就只执行str
        return "小元"

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

<5> __ call__ --triggered when the object is called, with brackets after the object: object () or class () ()

class A:

    def __init__(self):
        pass

    def __call__(self, *args, **kwargs):  # 对象()时调用的__call__
        print("走我")
        print(*args, **kwargs)

a = A()
a()

<6> __ eq__ equals

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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> __ del__ constructor, when the object is released in memory, it automatically triggers execution

This method generally 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, because the allocation and release of memory are handed over to the Python interpreter class, so, destruct The function call is automatically triggered by the interpreter during garbage collection.

class A:
    def __init__(self):
        pass

    def __del__(self):    del 触发
        print("删除时执行我")

a = A()

import time
time.sleep(5)
del a

a = 1
b = a
a = b

Garbage collection mechanism:

    # 80  5/s
    # 引用计数
    # 标记清除
    # 分袋回收 袋一:10 2/h  袋二: 5/3 4h  袋三: 3 20h

<8> __ item__ series can operate instance method like operating dictionary

dic["键"] =del dic["键"]
dic["键"]

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class A:

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

    def __getitem__(self, item):
        print(self.__dict__)
        print(self.__dict__[item])  # self.__dict__ 获取的就是字典

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

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

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

<9> __ new__ singleton mode (factory mode)

The singleton pattern is a commonly used software design pattern. It contains only a special class called singleton class in its core structure. The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easily accessible to the outside world, thereby facilitating the control of the number of instances and saving system resources. If you want only one object of a certain class to exist in the system, the singleton pattern is the best solution.

class A(object):

    def __init__(self,name):  # 初始化
        self.name = name
        print("我是__init__,先走我")

    def __new__(cls, *args, **kwargs):
        print("我是__new__,先走我")
        return "啦啦啦"

a = A("meet")
print("我是谁:",a)

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class A(object):

    def __init__(self,name):  # 初始化
        self.name = name
        print("我是__init__,先走我")

    def __new__(cls, *args, **kwargs):
        obj = object.__new__(A)
        print("我在哪:",obj)
        return obj                   # obj == __init__()

a = A("meet")
print("我是谁:",a)

class A(object):

    def __init__(self,name): # 初识化
        self.name = name


    def __new__(cls, *args, **kwargs):
        obj = object.__new__(A)   # 调用的是object类中的__new__ ,只有object类中的__new__能够创建空间
        return obj   #本质: obj == __init__()     return __init__()  # 触发了__init__方法


a = A("mee")  # a是对象的内存地址
a1 = A("天魔")  # a是对象的内存地址
a2 = A("天阳")  # a是对象的内存地址
print(a.name)
print(a1.name)
print(a2.name)

# 先执行__new__方法再执行__init__方法
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)  # 地址0x000001F346079FD0
a1 = A("天魔",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 the object is instantiated:

Create objects and open up object space __ next__

Automatically execute __ init method, implicitly pass 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) # 没有错误时就是None
        self.f.close()


with my_open("a.txt") as ffff:
    for i in ffff:
        print(i)
print(ffff.read(1111))
print(ffff.read())
Published 706 original articles · praised 885 · 1.55 million views +

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/105635050