15

我一直在我的代码中使用以下内容:

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'

我需要向我的班级添加什么才能使选项卡完成功能适用于属性?

4

1 回答 1

22

Add this method:

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

See here: http://ipython.org/ipython-doc/dev/config/integrating.html

And here: http://docs.python.org/2/library/functions.html

于 2012-12-14T00:21:03.413 回答