这是我的数据库管理器类:Python中有方法的匿名调用吗?
class DatabaseManager(object):
def __init__(self):
super().__init__()
self.conn = sqlite3.connect('artist.db')
self.c = self.conn.cursor()
def create_table(self):
self.c.execute(
'CREATE TABLE IF NOT EXISTS artists(title TEXT, artist TEXT, album TEXT, year INTEGER, '
'genre TEXT, ext TEXT, path TEXT, art TEXT)')
self.c.close()
self.conn.close()
def insert(self, song):
self.c.execute(
'INSERT INTO artists(title, artist, album, year, genre, ext, path, art) VALUES(?, ?, ?, ?, ?, ?, ?, ?)',
(song.title, song.artist, song.album, song.year, song.genre, song.ext, song.path, song.art))
self.conn.commit()
self.c.close()
self.conn.close()
def retrieve_all(self):
self.c.execute('SELECT * FROM artists')
data = self.c.fetchall()
self.c.close()
self.conn.close()
return data
还有更多的方法,但是这并不重要。当我启动应用程序时,我打电话给create_table()
,当我需要一些数据库操作时,我会创建另一个对象(或重新创建一个对象),例如调用insert
。
db = DatabaseManager()
print(db.retrieve_artist('asdf'))
db = DatabaseManager()
print(db.retrieve_all())
有什么办法可以避免这种情况吗?在Java中有匿名调用: new DatabaseManager().retrieve_artist("asdf")
在Python中有什么类似的可能吗?
检查Python中的'lamda'函数 –
你在Java中做什么与Python不同?你当然可以简单地跳过变量'DatabaseManager()。retrieve_artist('asdf')'。 – RemcoGerlich
虽然这是一个非常奇怪的API,但是创建一个对象会打开一个连接,调用一个方法关闭它,以至于不能再使用该对象。为什么? – RemcoGerlich