【问题标题】:Python's getattr gets called twice?Python 的 getattr 被调用了两次?
【发布时间】:2010-09-05 00:42:57
【问题描述】:

我通过这个简单的例子来理解 Python 的 getattr 函数:

In [25]: class Foo:
   ....:     def __getattr__(self, name):
   ....:         print name
   ....:         
   ....:         

In [26]: f = Foo()

In [27]: f.bar
bar
bar

为什么bar 会打印两次?使用 Python 2.6.5。

【问题讨论】:

  • 您使用的是什么版本。它适用于我在 2.6.5 上的新旧样式类。

标签: python reflection python-2.6 getattr


【解决方案1】:

我认为这是由于 IPython。

要“修复”它,您必须禁用自动呼叫:%autocall 0

这是不可避免的副作用 %autocall: 因为它必须分析 在命令行中查看对象是否 它是可调用的,python 触发 getattr 调用它。

来源:http://mail.scipy.org/pipermail/ipython-user/2008-June/005562.html

【讨论】:

    【解决方案2】:

    您也在使用 IPython。普通的 CPython REPL 不会出现这种行为。

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多