replace python parent function with child function -
i have problem in inheritance python.
i need override python function , whenever class called should call child method not parent.
here code : in file called test_inherit.py
class test_me(object):      def get_uid(self, node):         return uid and did : in file called test_new.py
from test_inherit import  test_me class test_new(test_me)      def get_uid(self,node):          print "x here",node          return uid i need when call test_me class or test_new class , should call get_uid of test_new class don't know how achieve ?!
it's simple .. have project has class "test_me" contain function called get_uid ,, , fuction called in project many times,i want call function of child when ever parent function called because don't want change main project ,, want edits in separate file .
subclassing changes behavior of child class has no effect on parent. class may have many inheritors , wouldn't clear subclass should called if could.
you can monkey-patch parent in following example. camel-cased class name stand out variable names. risk code called before patching gets old uid method.
class testme(object):      def get_uid(self, node):         return "parent"  test1 = testme() uid1 = test1.get_uid()  # monkey-patch 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" 
Comments
Post a Comment