How to Override a Class with a Function Nested in Python

Asked 2 years ago, Updated 2 years ago, 22 views

class name1(object):

    def method1(self):

       def method2():
           print 'Hi!'

       method2()

class name2(name1):

    Description that makes print 'Hi' in method2 to print 'Hello'

Please tell me how to write it.

python

2022-09-30 19:42

2 Answers

Reimplement the method1 itself.

method2 is part of the method1 code, so if you want to inherit the class and rewrite only a few lines of code for the parent class function, you need to "reimplement the entire parent class function."

If the "parent class function" has code that can be reused in subclasses, consider splitting it into multiple methods or module global functions and reusing them. Flat is better then nested..


2022-09-30 19:42

It looks like the following, but as you can see, I don't recommend it.

replace_inner_func.py

import new

class name1(object):
  def method1(self):
     def method2():
       print 'Hi!'
     method2()

class name2(name1):
  def__init__(self):
    def method2():
      print 'Hello!'

    m1 = self.method1
    m1_code = m1.func_code
    new_method=(None, method2.func_code)
    self.method1 = new.instancemethod(
      new.function(
        new.code(
          m1_code.co_argcount, m1_code.co_nlocals, m1_code.co_stacksize,
          m1_code.co_flags, m1_code.co_code, new_method, m1_code.co_names,
          m1_code.co_varnames, m1_code.co_filename, m1_code.co_name,
          m1_code.co_firstlineno, m1_code.co_lnotab),
        globals(),
      self, self.__class__)

if__name__=='__main__':
  n1 = name1()
  n2 = name2()
  n1.method1()
  n2.method1()


2022-09-30 19:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.