Advanced features of Python

1, Class method and static method

A class method is a method owned by a class object, which needs to be identified as a class method by a modifier, usually @ classmethod.
1). For class methods, the first parameter must be a class object as the first parameter
2). It can be accessed through instance objects and class objects.
Static methods need modifiers. Generally, @ staticmethod is used to identify them as static methods,
1). Static methods do not need to define more parameters
2). It can be accessed through instance objects and class objects.

class date(object):
    # Normal method: pass the object as a parameter to self
    def get_self(self):
        print('self:', self)

    # Class method: pass the class name as a parameter to cls
    def get_cls(cls):
        print('cls:', cls)

    # Static method: no parameters are passed automatically
    def get_static(name, age):
        print("Static method", name, age)

d = date()
d.get_static("Zhang San", 18)

The results are as follows:

2, property class properties

1. Basic introduction

Class attribute application requirements: For the list page of the computer host displayed in Jingdong Mall, it is impossible to display all the contents in the database on the page every request, but it is partially displayed through the paging function. Therefore, the specified information to be displayed when requesting data from the database is obtained from the second page m Articles to n The functions of this page include:
- It is calculated according to the current page and the total number of data requested by the user m and n
- according to m and n Request data from the database
class Page(object):
    [user1, user2, user3......user100]
    page=2, per_page=10
    first page: start=0 end=10
    Page 2: start=10 end=20
    Page 3: start=20 end=30
    The first page page: start=(page-1)*per_page end=page*per_page
    def __init__(self, page, per_page=10):  %here per_page Default parameters may not be specified = page
        self.per_page = per_page

    # Class attribute: the process of turning a class method into a class attribute.
    def start(self):
        return ( * self.per_page

    def end(self):
        return * self.per_page

if __name__ == '__main__':
    goods = ['good'+str(i+1) for i in range(100)]
    page = Page(page=10, per_page=3)

The results are as follows:

2. Simple cases

class date(object):
    def __init__(self, year, month, day):
        # Private property
        self.__year = year
        self.__month = month
        self.__day = day

    # The class method object Year() is transformed into the class attribute object Year, there is no need to add parentheses when calling, just to make the code more concise.
    def year(self):
        return  self.__year

today = date(2021, 2, 27)

The results are as follows:

3, Singleton mode

For some classes in the system, only one instance is very important. For example, there can be multiple print tasks in a system, but there can only be one working task; A system can only have one window manager or file system; A system can only have one timing tool or ID (sequence number) generator. For example, only one task manager can be opened in Windows. If you do not use the mechanism to make window objects unique, multiple Windows will pop up. If the contents displayed in these Windows are exactly the same, they are duplicate objects and waste memory resources; If the contents displayed in these Windows are inconsistent, it means that there are multiple states of the system at a certain moment, which are inconsistent with the actual situation. It will also bring misunderstanding to the user and do not know which is the real state. Therefore, sometimes it is very important to ensure the uniqueness of an object in the system, that is, a class can only have one instance

1. Understand singleton mode

What is singleton mode?
The design pattern that a class can only instantiate one object is called singleton pattern.

class People(object):

p1 = People()  # object
p2 = People()  # object
print(p1, p2)  # The memory address of each object is different. It is definitely not a singleton mode

The results are as follows:

2. Implement singleton mode based on decorator

from functools import wraps

def singleton(cls):
    # Store class and object information through a dictionary {"Class":"object"}
    instances = {}

    def wrapper(*args, **kwargs):
        # To ensure the singleton mode, judge whether the class has been instantiated as an object
        # 1. If there is an object, return the existing object directly
        # 2. If not, instantiate the object, store the class and object in the dictionary, and finally return the object
        if instances.get(cls):
            return instances.get(cls)
        object = cls(*args, **kwargs)
        instances[cls] = object
        return object

    return wrapper

@singleton       %If you remove this decorator p1 and p2 Will be different instances
class People(object):

p1 = People()
p2 = People()    %It has been instantiated, and there is already when it returns, so it does not need to be instantiated again
print(p1, p2)
print(p1 is p2)  # Judge whether it is in singleton mode (whether p1 and p2 memory addresses are the same)

The results are as follows:

3. Implement singleton mode based on new method

class People(object):
    _instance = None
    def __new__(cls, *args, **kwargs):   %new Method is actually creating an object
        """What was executed before the object was created"""
        if cls._instance is None:
            cls._instance = object.__new__(cls)
        return  cls._instance

    def __init__(self):
        """stay new Method, encapsulating the attributes and objects together"""
        print("Executing construction method init......")

p1 = People()
p2 = People()
print(p1, p2)

The results are as follows:

Posted by paldo on Thu, 14 Apr 2022 02:31:24 +0930