【问题标题】:Python call constructor in a member functionPython在成员函数中调用构造函数
【发布时间】:2012-01-10 17:30:45
【问题描述】:

我们以这个类为例,它扩展了 MySQLDB 的连接对象。

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

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

在标有注释的行中,是否可以在 Python 中调用对象构造函数,即使这是一个成员函数?我使用此示例进行说明,因为如果在运行查询之前超时断开连接,它将有效地重新建立连接。

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

【问题讨论】:

    标签: python oop constructor


    【解决方案1】:

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

    这是因为__init__并不是真正的对象的构造函数,它更像是你的实例的“初始化器”,真正的构造函数是__new__方法,它负责实例的创建。

    【讨论】:

      猜你喜欢
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      相关资源
      最近更新 更多