【问题标题】:Overriding the instance next function覆盖实例下一个函数
【发布时间】:2017-01-05 15:03:53
【问题描述】:

我正在尝试使用下面的代码 (python 2.7) 覆盖对象的下一个函数。

直接调用对象的next方法时,会调用新函数。然而,当我在我的对象上调用内置的 next() 函数(according to the docs 应该调用实例的 next 方法)时,会调用 ORIGINAL 函数。

有人可以解释这种行为吗?

class Test(object):
    def __iter__(self):
        return self
    def next(self):
        return 1

test = Test()
def new_next(self):
    return 2

test.next = type(test.__class__.next)(new_next, test, test.__class__)
print test.next() # 2
print next(test) # 1

【问题讨论】:

  • 有趣。可能与PEP 3114有关?
  • @AndréLaszlo 看起来 PEP 适用于 Python 3
  • @warvariuc 哎呀,你是对的。

标签: python


【解决方案1】:

如果我正确阅读this source,似乎在定义类时设置了迭代器。不过我可能读错了。我猜这是为了快速查找next 函数(将其设置为slot),因为它用于循环等。

鉴于此,以下似乎可以满足您的需求:

>>> test.__class__.next = type(test.__class__.next)(new_next, test, test.__class__)
>>> next(test)
2

【讨论】:

  • 谢谢!实际上,当我动态地创建一个继承自 Test 的类并在那里重写 next 方法时,我实际上采用了一种不同的方法。这样我就不会改变原来的类。
  • 听起来更安全,而不是依赖于一些无证行为和一些半猜测的人:)非常有趣,感谢发帖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多