__getitem__,__setitem__多重键Python [英] __getitem__, __setitem__ multiple keys Python

查看:243
本文介绍了__getitem__,__setitem__多重键Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a class that stores data in a local buffer as well as acts as an interface to a database. I've got following code:

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"

另一方面,此更新而不是覆盖表:

It does nothing, on the other hand this updates rather than overwrites the table:

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



我知道我必须重写updateBufferRow()和getBufferRow()方法,相当肯定是如何使用__getitem__和__setitem__方法获取多个键
任何帮助/提示将非常感谢。

I know I have to rewrite updateBufferRow() and getBufferRow() methods, the only thing I am not quite sure is how to get multiple keys using __getitem__ and __setitem__ methods Any help/hints will be greatly appreciated. Thank you guys!

推荐答案

您的<$ c>返回的 dict $ c> __ getitem __ 与您的列没有任何关系。你需要返回一个看起来像 dict 但是映射 __ setattr __ 的回调到你的表列: / p>

The dict returned by your __getitem__ has no relation any more with your columns. You'll need to return something that perhaps looks like a dict but maps __setattr__ calls back to your table columns:

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)

这篇关于__getitem__,__setitem__多重键Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆