Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding the instance next function

Tags:

python

I'm trying to override an object's next function using the code below (python 2.7).

When the object's next method is called directly, the new function is invoked. However when I call the builtin next() function on my object (which, according to the docs, should call the instance's next method), the ORIGINAL function is invoked.

Can someone explain this behaviour?

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
like image 431
Tzach Avatar asked Jan 05 '17 15:01

Tzach


People also ask

Are instance methods overridden?

An instance method that is defined in a subclass is said to override an inherited instance method that would otherwise be accessible in the subclass if the two methods have the same signature.

How do you override a function?

Overriding occurs in a parent class and its child class. No special keyword is used to overload a function. Virtual keyword in the base class and Override keyword in the derived class can be used to override a function.

What happens when you override a function?

Function overriding in C++ is a feature that allows us to use a function in the child class that is already present in its parent class. The child class inherits all the data members, and the member functions present in the parent class.

What does @override mean in Java?

The @Override annotation is one of a default Java annotation and it can be introduced in Java 1.5 Version. The @Override annotation indicates that the child class method is over-writing its base class method.


1 Answers

If I'm reading this source correctly it seems like the iterator is set when the class is defined. I might read it wrong though. I'm guessing it's for fast lookup of the next function (setting it as a slot) since it's used in loops etc.

Given that, the following seems to do what you're after:

>>> test.__class__.next = type(test.__class__.next)(new_next, test, test.__class__)
>>> next(test)
2
like image 175
André Laszlo Avatar answered Oct 10 '22 17:10

André Laszlo