自定义dict类的ipython选项卡完成

时间:2012-12-13 23:17:11

标签: python

我在代码中使用了以下内容:

class Structure(dict,object):
""" A 'fancy' dictionary that provides 'MatLab' structure-like
referencing. 

"""
def __getattr__(self, attr):
    # Fake a __getstate__ method that returns None
    if attr == "__getstate__":
        return lambda: None
    return self[attr]

def __setattr__(self, attr, value):
    self[attr] = value

def set_with_dict(self, D):
    """ set attributes with a dict """
    for k in D.keys():
        self.__setattr__(k, D[k])

总而言之,它适用于我的目的,但我注意到,只有方法选项卡完成才能用于继承自Structure的另一个自定义类中的方法,而不是属性。我也做了这个测试,我发现结果有点奇怪:

In [2]: d = Structure()
In [3]: d.this = 'that'
In [4]: d.this
Out[4]: 'that'
In [5]: d.th<tab>
NOTHING HAPPENS

In [6]: class T():
   ...:     pass
   ...: 

In [7]: t = T()
In [8]: t.this = 'cheese'
In [9]: t.th<tab>
COMPLETES TO t.this
Out[9]: 'cheese'

我需要将哪些内容添加到我的类中才能使标签完成工作以获取属性?

1 个答案:

答案 0 :(得分:16)

添加此方法:

def __dir__(self):
    return self.keys()

见这里:http://ipython.org/ipython-doc/dev/config/integrating.html

在这里:http://docs.python.org/2/library/functions.html