Python调用构造函数在成员函数中 [英] Python call constructor in a member function

查看:1335
本文介绍了Python调用构造函数在成员函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类DBHandler(mysql.connections.Connection) :
def __init __(self,cursor = None):
如果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是问题中的行
pass


def execute(self,q,params):
cur = self.cursor()
cur.execute(q,params)
self.commit()
return cur。 lastrowid

这很大程度上是为了更简单地访问常见的所需查询。



在标有注释的行上,是否可以在Python中调用对象构造函数,即使这是一个成员函数?我使用这个例子来说明,因为它会有效地重新建立连接,在事件中,它在运行查询之前超时超时。



我知道MySQLdb的 ping()方法,这只是一个能力的问题。 在python中,是否可以从实例上调用的成员函数中调用构造函数来重新初始化该实例?谢谢!

解决方案

是的,你可以,因为最好是在另一个方法中提取你的初始化代码( def init(self):) 。



这是因为 __ init __ 不是真正的对象的构造函数,它更多的是你的实例的初始化器,真正的构造函数是 __ new __ 方法,负责创建实例。


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.

这篇关于Python调用构造函数在成员函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆