我使用的是python2.7,我编写了一组python类,以便将数据上载到数据库。然而,我不确定我是否完全理解如何在类与类之间使用继承。我有一个User和Database类,它从一个列表中搜索用户/数据库:class User(object):
user_lst = ['user1', 'user2', 'user3']
def __init__(self, username):
self.username = username
def find_user(self):
if self.username not in self.user_lst:
print('User not found, script will exit')
exit()
else:
pass
class Database(object):
db_lst = ['db1', 'db2', 'db3']
def __init__(self, database):
self.database = database
def find_db(self):
if self.database not in self.user_lst:
print('Database not found, script will exit')
exit()
else:
pass
我使用raw_input()获取用户和数据库的值,它返回:
^{pr2}$
要按照我的理解实例化这些类,我需要通过类传递这些值,此时我还可以调用方法-User(un).find_user()
Database(db).find_db()
现在我想使用第三个类来继承这些值,以便连接到数据库:class DatabaseConnect(User, Database):
def __init__(self):
User.__init__(self, username)
Database.__init__(self, database)
def connect(self, pw):
try:
connect = MySQLdb.connect(host = 'localhost', user = self.username, passwd = pw, db = self.database, local_infile = 1)
cursor = connect.cursor()
print('Connected to '+self.database)
except:
print('Did not connect to database')
exit()
然后我尝试使用以下方式连接:DatabaseConnect().connect('password1')
但是这不起作用。我试图将DatabaseConnect类的init函数添加到数据库中:def __init__(self, username, database):
User.__init__(self, username)
Database.__init__(self, database)
我还尝试过从这些类创建对象变量,例如:user_obj = User(un)
user_obj.find_user()
db_obj = Database(db)
db_obj.find_user()
我需要创建这些对象变量,然后通过我的DatabaseConnection类传递它们吗?如果需要,我甚至需要继承吗?这就是我困惑的原因。假设我使用这些对象变量并使用这个类:class DatabaseConnect(User, Database):
def __init__(self, username, database):
self.username = User.username
self.database = Database.database
def connect(self, pw):
try:
connect = MySQLdb.connect(host = 'localhost', user = self.username, passwd = pw, db = self.database, local_infile = 1)
cursor = connect.cursor()
print('Connected to '+self.database)
except:
print('Did not connect to database')
exit()
然后我用以下方法实例化它:db_connect = DatabaseConnect(user_obj, db_obj)
这与简单地使用变量本身有何不同:db_connect = DatabaseConnect(un, db)
为什么我必须使用:self.username = User.username
而不是简单地:self.username = username
我正在努力让我的头脑围绕这个概念,所以任何人都会感激。谢谢