python 类方法的好处_求教大牛看下这个python类方法的作用是什么

class BaseDB:

'''

BaseDB

dbcur should be overwirte

'''

__tablename__ = None

placeholder = '%s'

maxlimit = -1

@staticmethod

def escape(string):

return '`%s`' % string

@property

def dbcur(self):

raise NotImplementedError

escape函数是干什么的,看起来像是返回一段字符串

dbcur怎么用来调用的呢,上面说dbcur应该重写,在子类中重写吗,然后怎么调用啊

pyspider代码

https://github.com/binux/pysp...

escape 是给string添加``符号。比如你创建的table或者column里有空白字符时。create table `hello world tb` (`column name1` INT NOT NULL AUTO_INCREMENT PRIMARY KEY)

错误的查询:select column name1 from hello world tb

正确的查询:select`column name1`from`hello world tb`

dbcur这个函数抛出未实现这个异常,目的是为了充当接口,由子类去实现。Python里面没有接口这个概念,所以定义接口时,可以采用这种方式。DbBase只付责构建sql语句,具体使用何种数据库由子类实现,好处是可以适配不同的数据库。

源码:if __name__ == "__main__":

import sqlite3

class DB(BaseDB):

__tablename__ = "test"

placeholder = "?"

def __init__(self):

self.conn = sqlite3.connect(":memory:")

cursor = self.conn.cursor()

cursor.execute(

'''CREATE TABLE `%s` (id INTEGER PRIMARY KEY AUTOINCREMENT, name, age)'''

% self.__tablename__

)

@property

def dbcur(self):

return self.conn.cursor()

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd13702.html

相关文章 Recommend

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值