覆盖实例下一个函数

Tza*_*ach 8 python

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

next直接调用对象的方法时,将调用新函数.但是当我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
Run Code Online (Sandbox Code Playgroud)

And*_*zlo 5

如果我正确地读取这个源,似乎在定义类时设置了迭代器.我可能会读错了.我猜这是为了快速查找next函数(将其设置为一个插槽),因为它用于循环等.

鉴于此,以下似乎做了你想要的:

>>> test.__class__.next = type(test.__class__.next)(new_next, test, test.__class__)
>>> next(test)
2
Run Code Online (Sandbox Code Playgroud)

  • http://stackoverflow.com/questions/34490998/why-typex-enter-x-instead-of-x-enter-in-python-standard-context/34491119#34491119 https://docs.python.org/3 /reference/datamodel.html#special-method-lookup (2认同)