Mostafa Mohamed Mostafa Mohamed - 2 years ago 173
Python Question

replace python parent function with child function

I have a problem in inheritance with python.

I need to override a python function and whenever that class called it should call the child method not the parent.

Here is the code :
in file called

class test_me(object):

def get_uid(self, node):
return uid

and what i did is :
in file called

from test_inherit import test_me
class test_new(test_me)
def get_uid(self,node):
print "X is here",node
return uid

i need that when i call test_me class or test_new class , it should call the get_uid of test_new class but i don't know how to achieve that ?!

It's simple .. i have a project that has this class "test_me" which contain a function called get_uid ,, and that fuction is called in the project many times,i want to call the function of the child when ever the parent function is called because i don't want to change the main project ,, i want to do my edits in separate file .

Answer Source

Subclassing changes the behavior of the child class but that has no effect on the parent. A class may have many inheritors and it wouldn't be clear which subclass should be called even if you could.

You can monkey-patch the parent as in the following example. I camel-cased the class name to help is stand out from variable names. The risk is that code called before the patching gets the old uid method.

class TestMe(object):

    def get_uid(self, node):
        return "parent"

test1 = TestMe()
uid1 = test1.get_uid()

# monkey-patch to modify parent class
def _my_get_uid(self, node):
    print "Parent hacked", node
    return "hack"
TestMe.get_uid = _my_get_uid

test2 = TestMe()

assert uid1 == "parent", "cant change old calls"
assert test1.get_uid(1) == "hack", "existing objects changed"
assert test2.get_uid(1) == "hack", "new objects changed"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download