【问题标题】:ipython tab completion for custom dict class自定义 dict 类的 ipython 选项卡完成
【发布时间】:2012-12-13 23:17:10
【问题描述】:

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

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'

我需要在我的类中添加什么才能使选项卡完成功能适用于属性?

【问题讨论】:

  • 如果你想要点访问而不是括号索引,而不是除了,你可以只使用object的空子类。默认情况下,Python 对象是“开放的”。 x.set_with_dict() 可以替换为x.__dict__.update()
  • 另外,从dictobject 继承是多余的,因为dict(和大多数标准库类)是新型类并且已经从object 继承。
  • 关于多重继承的要点。但是,我确实希望 both 括号和点访问我的键。我正在尝试将我的代码切换为使用纯 python dict,但仍有相当多的地方依赖点访问...

标签: python


【解决方案1】:

添加这个方法:

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

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

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

【讨论】:

  • 感谢goodside!我在之前的搜索中错过了那条信息(不确定如何)!
  • 在较新的 IPython 中,选项卡完成窗口似乎有一些最大数量的滚动条目。有人知道如何调整吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 2012-06-12
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多