2014-12-06 74 views
2

下面是示例代码,它提供了我希望获得修复帮助的错误,或者了解更好的写入方法。我有一个名为mysql_connection的mysql“超级”类。在这个类中,连接到数据库。我也有一些方法。简单地运行“select version()”来显示连接/查询的工作原理。然后我有一个“chktable”方法,在这个例子中实例化一个名为“table”的新子类,它继承了超类。在实例化类之后,我调用了子类中的一个方法,该方法尝试使用超类中的查询方法来运行“show tables like'tbl name'”。这是我得到一个错误。Python使用超级类的mysql连接

import mysql.connector 
from mysql.connector import errorcode 
from mysql.connector.cursor import MySQLCursor 

class mysql_connection(object): 
    def __init__(self, **kwargs): 
     self.connection_options = {} 
     self.connection_options['user'] = 'root' 
     self.connection_options['password'] = '' 
     self.connection_options['host'] = '192.168.33.10' 
     self.connection_options['port'] = '3306' 
     self.connection_options['database'] = "test" 
     self.connection_options['raise_on_warnings'] = True 
     self.connect() 

    def connect(self): 
     try: 
      self.cnx = mysql.connector.connect(**self.connection_options) 
     except mysql.connector.Error as err: 
      if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: 
       print "Something is wrong with your user name or password" 
      elif err.errno == errorcode.ER_BAD_DB_ERROR: 
       print "Database does not exists" 
      else: 
       print err 

    def query(self, statement, data=''): 
     cursor = MySQLCursor(self.cnx) 
     cursor.execute(statement) 
     result = cursor.fetchall() 
     cursor.close 
     return result 

    def get_version(self): 
     print self.query("select version()") 

    def chktable(self, tb_name): 
     tab = table(name=tb_name) 
     tab.check_table() 

class table(mysql_connection): 
    def __init__(self, **kwargs): 
     self.name = kwargs['name'] 

    def check_table(self): 
     return super(table, self).query("show tables like '{}".format(self.name)) 

conn = mysql_connection() 
conn.get_version() 
conn.chktable("test") 

,我得到的错误是:

$ python example.py 
[(u'5.1.73',)] 
Traceback (most recent call last): 
    File "example.py", line 50, in <module> 
    conn.chktable("test") 
    File "example.py", line 39, in chktable 
    tab.check_table() 
    File "example.py", line 46, in check_table 
    return super(table, self).query("show tables like '{}".format(self.name)) 
    File "example.py", line 28, in query 
    cursor = MySQLCursor(self.cnx) 
    AttributeError: 'table' object has no attribute 'cnx' 

我不完全理解回调到超类,以及它如何与子类的作品,所以很可能我的问题。我也想知道是否有更好的方法来实现这一点。我想我可以完全摆脱子类,但我喜欢我创建的子类,所以我觉得应该有办法解决它。我可以尝试的第二件事是将子类放在主类中,但我认为这不正确。

+1

为什么你的表从连接继承? – jonrsharpe 2014-12-06 09:04:14

回答

2

正如乔恩指出的那样,这不是继承的恰当用法。这是为了“是 - 一个”关系:即狗从动物继承,因为狗是动物。但是表格不是连接:表格可能使用连接,但这仅仅意味着您应该将连接的实例分配给表格中的实例变量。

另外,在继承关系中,通常没有什么理由让超类知道它的子类,就像在chktable方法中一样。

(你看到实际的错误是因为你没有叫表的__init__超类的方法,但它更好地解决您的结构。)

+0

谢谢。你是正确的,它不是一个适当的继承使用。尽管这只是一个例子,而且在实际代码中mysql_connnection类的命名方式不同,我的类是“有”组合,而不是“是”。随着对代码的进一步思考,我意识到我不会在其他地方使用“拥有”类,所以我只是将它添加到主类中。我可能会去做一个实际的mysql连接组合类来从我正在处理的主要mysql类中解耦它。 – david 2014-12-07 15:43:38

+0

很好的解释何时使用继承以及如何处理这种情况,而不使用和实例变量 – 2016-06-07 23:21:23