5

我正在尝试创建一个将数据存储在本地缓冲区中并充当数据库接口的类。我有以下代码:

class Table(object):    
    def __init__(self, tableName, **columnDict):
       self.tableName      = tableName
       self.columns        = {}
       self.types          = {}
       self.columns['id']  = []
       self.types['id']    = 'INT PRIMARY KEY NOT NULL'
       for name in columnDict:
           self.columns[name] = []
           self.types[name]    = columnDict[name]

    def updateBufferRow(self, index, updateDict):
       for key in updateDict:
           self.columns[key][index] = updateDict[key]

    def getBufferRow(self, index):
       row = {}
       for key in self.columns:
           row[key] = self.columns[key][index]
       return row

    def __getitem__(self, key, **args):
       """ Allows using self[key] method """
       return self.getBufferRow(key)

    def __setitem__(self, key, value, **args):
       """ Allows using self[key] = value method """
       self.updateBufferRow(key, value)

这是我初始化表的方式:

testTable = Table('BestTable', test = 'TestType', test2='INT')

如果我尝试,它会按预期工作:

testTable[0]['test'] = "LALALA"

它什么也不做,另一方面,它更新而不是覆盖表:

testTable[0] = {"test": "LALALA"}

我知道我必须重写 updateBufferRow() 和 getBufferRow() 方法,唯一我不太确定的是如何使用 _ getitem _ 和 _ setitem _ 方法获取多个键。

4

1 回答 1

3

dict您返回的与__getitem__您的列不再有任何关系。您需要返回一些可能看起来像dict但将调用映射__setattr__到表列的内容:

class Row(dict):
    def __init__(self, table, index, *args, **kw):
        self._table, self._index = table, index
        super(Row, self).__init__(*args, **kw)

    def __setitem__(self, key, value):
        super(Row, self).__setitem__(key, value)
        self._table.columns[key][self._index] = value

然后返回它而不是常规dict

def getBufferRow(self, index):
   row = {}
   for key in self.columns:
       row[key] = self.columns[key][index]
   return Row(self, index, row)
于 2013-03-14T19:09:14.150 回答