Python (thirteen) - advanced object-oriented features

1. Class attributes and instance attributes

The class attribute is the attribute possessed by the class object, it is shared by all the instance objects of the class object, and there is only one copy in the memory.

2. Class methods and static methods

  • A class method is a method owned by a class object, and a decorator is generally used to identify it as a class method.
    1). For a class method, the first parameter must be a class object, as the first parameter
    (cls is the form The parameters can be modified to other variable names, but it is better to use'cls')
    2). It can be accessed through instance objects and class objects.
  • Static methods need to be decorated with @staticmethod 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.
"""
相关的源码:from datetime import  datetime
"""

class Student(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # 实例方法, python解释器会自动将对象/实例传入方法。
    def get_age(self):
        print('self:', self)
        return  self.age

    # 类方法:python解释器会自动将类传入方法。
    @classmethod
    def get_cls(cls):
        print('cls:', cls)

    # 静态方法:python解释器不会自动传入任何参数
    @staticmethod
    def get_info():
        print("static method信息")

if __name__ == '__main__':
    s = Student('张三', 18)
    s.get_age()
    s.get_cls()
    s.get_info()

Insert picture description here

3. Property class attributes

  • A special attribute that is used as an instance attribute can correspond to a method of a class.
    The definition and call of the property attribute should pay attention to the following points:
    1. When defining, add the @property decorator on the basis of the instance method; and there is only one self parameter
    2. When calling, no parentheses are required

  • Class attribute application requirements: For the list page that displays the computer host in the Jingdong Mall, it is impossible to display all the content in the database on the page every time it is requested, but is displayed partially through the paging function, so when requesting data from the database The paging function of specifying to get all the data from the mth to the nth to be displayed includes:
    1. Calculate m and n
    according to the current page requested by the user and the total number of data. 2. Go to the database according to m and n Request data

  • There are two ways of property attribute:
    1. Decorator means: apply decorator on method
    2. Class attribute means: define the class attribute whose value is the property object in the class

  • Note:
    1. The property in the classic class has only one access method, which corresponds to the method modified by @property.
    2. The property in the new-style class has three access methods, which correspond to three @property and @methodname.setters respectively. , @Method name.deleter modified method

##简单案例

class date(object):
    def __init__(self,year,month,day):
        #私有属性
        self.__year = year
        self.__month = month
        self.__day = day
    @property     #将类方法转换成了类属性,只是让代码更加简洁而已
    def year(self):
        return self.__year
today = date(2021,2,27)
#print(today.year())   #2021  #不添加proptory装饰器的情况,可以简化代码(少了个括号)
print(today.year)   #2021     ##添加了装饰器的结果

"""
类属性应用需求: 对于京东商城中显示电脑主机的列表页面,每次请求不可能把数据库中的所有内容都显示到页面上,而是通过分页的功能局部显示,所以在向数据库中请求数据时就要显示的指定获取从第m条到第n条的所有数据 这个分页的功能包括:
- 根据用户请求的当前页和总数据条数计算出 m 和 n
- 根据m 和 n 去数据库中请求数据

from datetime import  datetime
"""

class Page(object):
    """
    [user1, user2, user3......user100]
    page=2, per_page=10
    第一页: start=0 end=10
    第二页: start=10 end=20
    第三页: start=20 end=30
    ....
    第page页: start=(page-1)*per_page end=page*per_page
    """
    def __init__(self, page, per_page=10):
        self.page = page
        self.per_page = per_page

    # 类属性: 将类方法变成类属性的过程。
    @property
    def start(self):
        return (self.page-1) * self.per_page

    @property
    def end(self):
        return  self.page * self.per_page

if __name__ == '__main__':
    goods = ['good'+str(i+1) for i in range(100)]
    page = Page(page=10, per_page=3)
    print(goods[page.start:page.end])
"""
类属性应用需求: 对于京东商城中显示电脑主机的列表页面,每次请求不可能把数据库中的所有内容都显示到页面上,而是通过分页的功能局部显示,所以在向数据库中请求数据时就要显示的指定获取从第m条到第n条的所有数据 这个分页的功能包括:
- 根据用户请求的当前页和总数据条数计算出 m 和 n
- 根据m 和 n 去数据库中请求数据

from datetime import  datetime
"""

class Page(object):
    """
    [user1, user2, user3......user100]
    page=2, per_page=10
    第一页: start=0 end=10
    第二页: start=10 end=20
    第三页: start=20 end=30
    ....
    第page页: start=(page-1)*per_page end=page*per_page
    """
    def __init__(self, page, per_page=10):
        self.page = page
        self.per_page = per_page

    # 类属性: 将类方法变成类属性的过程。
    @property
    def start(self):
        return (self.page-1) * self.per_page

    @property
    def end(self):
        return  self.page * self.per_page

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

4. Singleton mode (a kind of design pattern)

  • Simply put, it is a design pattern in which a class can only construct one object.
  • For some classes in the system, only one instance is 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 (serial number) generator. For example, only one task manager can be opened in Windows. If you do not use a mechanism to uniqueize the window object, multiple windows will pop up. If the content displayed in these windows is exactly the same, it is a duplicate object, wasting memory resources; if the content displayed in these windows is inconsistent, it means that at a certain moment The system has multiple states, which are inconsistent with the actual state, and will also cause misunderstandings to users, and they do not know which one is the real state. Therefore, it is sometimes very important to ensure the uniqueness of an object in the system, that is, a class can only have one instance.

4.1 Understand the singleton pattern

##理解单例模式
"""
什么是单例模式?
一个类只能实例化一个对象的设计模式称为单例模式。
"""

class People(object):
    pass

p1 = People()  # object
p2 = People()  # object
print(p1, p2)  # 每个对象的内存地址不同,肯定不是单例模式

4.2 Implementation of singleton mode based on decorators

from functools import  wraps
def singleton(cls):
    # 通过一个字典存储类和对象信息{"Class":"object"}
    instances = {
    
    }
    @wraps(cls)
    def wrapper(*args, **kwargs):
        # 为了保证单例模式, 判断该类是否已经实例化为对象
        # 1. 如果有对象,直接返回存在的对象
        # 2. 如果没有则实例化对象, 并存储类和对象到字典中, 最后返回对象
        if instances.get(cls):
            return instances.get(cls)
        object = cls(*args, **kwargs)
        instances[cls] = object
        return  object
    return  wrapper

@singleton
class People(object):
    pass


p1 = People()
p2 = People()
print(p1, p2)
print(p1 is p2)  # 判断是否为单例模式(p1和p2内存地址是否相同)

4.3 Singleton mode based on the new method

class People(object):
    _instance = None
    def __new__(cls, *args, **kwargs):
        """创建对象之前执行的内容"""
        if cls._instance is None:
            cls._instance = object.__new__(cls)
        return  cls._instance

    def __init__(self):
        """在new方法之后执行, 将属性和对象封装在一起"""
        print("正在执行构造方法init......")

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

4.4 Summary

"""
面向对象:
    1. 三大特性
        封装(必须要掌握的):
            __new__: 在实例化对象之前执行的, 返回对象。
            __init__: 构造方法, 实例化对象时自动执行。 常用于将对象和属性绑定在一起。
            self: 实质上是对象。
        继承(最多知识点的):
            多继承算法: python3中广度优先算法。
            私有属性和私有方法
        多态(最简单的):

    2. 三大特性的应用
        1). 链表的封装(Leetcode第二题)
        2). 栈的封装
        3). 队列的封装
        4). 二叉树的封装与先序遍历

    3. 高级特性
        1). @classmethod和@staticmethod(类方法和静态方法)
        2). @property类属性
        3). 单例模式: 一个类只能实例化一个对象
            基于装饰器
            基于new方法
"""

Guess you like

Origin blog.csdn.net/qwerty1372431588/article/details/114179896