我正在尝试创建一个将数据存储在本地缓冲区中以及充当数据库接口(interface)的类。我有以下代码:
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_方法获取多个键。 最佳答案
您的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)
关于python - __getitem __,__ setitem__多个键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15417962/