python 3——自定义一个类、object类

 1.如何创建一个类?

自定义一个类:(https://www.runoob.com/python3/python3-class.html)

__init__(self):

 

  self代表类的实例,而非类

  类的方法:在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self, 且为第一个参数,self 代表的是类的实例。

 

 

  #私有的东西外部不能调用 

 

举例:

  ORM中对于raw-queryset的分页是不能用分页器的,所以我们自建一个封装sql的分页类,调用即可

# 1.获取数据库连接
from django.db import connection

class SqlPaginator(object):     #python3可以不写,默认继承
    #实现sql分页类:
    def __init__(self, sql, params, page_size):
        super().__init__()
        self.sql = sql      #要查询的sql
        self.params = params    #sql查询时候传递的参数
        self.page_size = page_size      #每页多少条数据

    def page(self, now_page):
        """
        获取当前页:
        :param now_page: 页码
        """
        offset = (page - 1) * self.page_size  # 偏移量:每页的首位置
        sql = self.sql + ' limit %s offset %s'      #不要漏了sql的空格

        # 使用cursor:
        sql = ('select `id`, `username`, `nickname` from `weibo_user`'
               'where `username` = %s'
               )
        # 2。根据连接获取游标
        cursor = connection.cursor()
        # 3。根据游标执行sql
        rest = cursor.execute(sql, [self.page_size, offset])
        # 4。获取查询结果
        rows = cursor.fetchall()
        return rows

object类是什么?

https://blog.csdn.net/qq_27828675/article/details/79358893

在python3不写会默认调用:

 

   

猜你喜欢

转载自www.cnblogs.com/marvintang1001/p/11068386.html