python调用类的成员函数_Python调用构造函数在成员函数中

1586010002-jmsa.png

Let's take for example this class, which is extending MySQLDB's connection object.

class DBHandler(mysql.connections.Connection):

def __init__(self,cursor=None):

if cursor == None:

cursor = 'DictCursor'

super(DBHandler,self).__init__(host = db_host,

user = db_user,

passwd = db_pass,

db = db,

cursorclass=getattr(mysql.cursors, cursor))

def getall(self,q,params=None):

try:

cur = self.cursor()

cur.execute(q,params)

res = cur.fetchall()

return res

except mysql.OperationalError:

#this is the line in question

pass

def execute(self,q,params):

cur = self.cursor()

cur.execute(q,params)

self.commit()

return cur.lastrowid

This thing is largely a convenience to get simpler access to common required queries.

On the line marked with the comment, is it possible in Python to recall the object constructor, even though this is a member function? I use this example to illustrate because it would effectively reestablish the connection in the event it is dropped on timeout before a query is run.

I'm aware of MySQLdb's ping() method, this is really just a question of capability. In python, Is it possible to call a constructor from within a member function called on an instance to re-initialize that instance? Thanks!

解决方案

Yes, you can, since it would be preferable to extract your initialization code in another method (a def init(self):).

This is because __init__ is not really the constructor of the object, it is more the "initializer" of your instance, the real constructor is the __new__ method, that is responsible of the instance creation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值