-2

I am having a class and a object for that class. Problem is when I have to make changes in the class methods, I have to kill the object and initiate another object. Is there a way I can get the modified functionality without killing object

Class ABC:
    def abc():
        print "Hello I am original text"

I am calling the class as

import ABC
obj = ABC()

obj.abc() is printing the desired output

If I want to make changes in the method abc or write a new method for the class, I have to reopen the python shell and have a new obj.

I am looking for a way where I can reload the class again and same object will have new properties of the class

I am using Python 2.7 and tried few things that I got like reload(module)

Giving negative rating is fine but there should be a reason for that. Just like if you don't have answer to that or does not understand it well, won't qualify you to give negative rating

Sumit
  • 1,953
  • 6
  • 32
  • 58

1 Answers1

0

okay, here is an answer.

But first a caveat. Doing this is a bad idea. Normally I'd say, write a test suite, write a module, test the module (somewhere where the hardware won't explode at the slightest touch?) and then apply.

Start with this question. You'll also need functools.partial.

The strategy is to write extra functions as if they were methods and monkey patch them to the object. Please note that i'm using python 3, but this should work fine in python 2.

I'll make two modules. base_class.py and new_methods.py. assume that each method in new_methods.py is written after the others and the module needs to be reloaded a lot.

base_class.py:

class MyClass(object):
    def __init__(self):
        self.a = 'a'
        self.b = 'b'

    def show_a(self):
        return self.a

new_methods.py:

def first(obj):
    return obj.b


def second(obj):
    return obj.a + obj.b


def third(obj, number):
    return obj.a + str(number)

interpreter:

>>> from base_class import MyClass
>>> x = MyClass()
>>> x.show_a()
'a'
>>> import sys
>>> from functools import partial
>>> import new_methods as nm
>>> x.show_a = partial(nm.first, x)
>>> x.show_a()
'b'
>>> del sys.modules['new_methods']  # wrote some new stuff. want to import
>>> import new_methods as nm
>>> x.show_a = partial(nm.third, x)
>>> x.show_a(5)
'a5'

If reloading doesn't work using this method, that answer above is pretty detailed about how to go about it.

e.s.
  • 1,351
  • 8
  • 12