嵌套类访问外部类的属性

时间:2020-05-06 09:07:40

标签: python mysql-python

我正在尝试使用外部类的光标将内部类对象保存到数据库中。

问题是,如果我在外部使用游标作为参数来实现User类,它会错误地接收任何游标作为参数,并且我希望仅在这个SpecialDatabase上下文内创建User。

这是我的课程的一个示例:

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")
...

有没有办法做到这一点?

编辑:添加了两个类的初始化

0 个答案:

没有答案