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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With