I'm trying to save an Inner class object into the database with the cursor of the outer class.
The thing is if I implement the class User outside with cursor as a parameter, it can receive any cursor as parameter by mistake, and I want User to be created only inside this SpecialDatabase context.
This is an example of my classes:
import MySQLdb
class SpecialDatabase():
def __init__(self, dbinfo):
self._dbinfo = dbinfo
def __enter__(self):
self._conn = MySQLdb.connect(**self._dbinfo)
self._cursor = self._conn.cursor()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
try:
self._cursor.close()
self._conn.close()
except AttributeError:
print('Not closable.')
return True
# User is an object of this database
class User():
...
def change_name(self, name):
stmt = '''UPDATE users SET name=%s WHERE id=%s'''
data = (name, self.id)
# I want to execute something like this,
# but I don't know how to reference the cursor from the outer
outer._cursor.execute(stmt, data)
...
# EDIT
dbinfo = {'host':'***', 'user':'***', 'passwd':'***', 'db':'***'}
db = SpecialDatabase(dbinfo)
...
user = db.User(id)
user.change_name("Bob")
...
Is there a way to do this?
EDIT: Added initialization of both classes