-1

How can I 'update' a class that has already been declared? My particular scenario is allowing a user to enter code (via a module name) during runtime to update the class when the program determines that the existing class is insufficient. So let's say I have module ClassA containing

class ClassA:
   def __init__(self, field1):
         self.field1 = field1

partway through runtime I notice some cases where I'd like to use ClassA if only I could add another field. I alert the user to this and give them the option. What can I prompt them to input? Is it possible for them to give me a filename redeclaring the class? If not, how else would I be able to do this? And if the user does this, what happens to existing instances of the class? I assume they are seamlessly updated if this is done correctly?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
sunny
  • 3,853
  • 5
  • 32
  • 62
  • 1
    Could you be a bit more specific about what you're trying to achieve? You can certainly add arbitrary attributes to an instance at runtime, but that won't affect other instances of the class (already-created or otherwise). – jonrsharpe Mar 06 '16 at 23:05
  • An approach like http://stackoverflow.com/questions/962962/python-changing-methods-and-attributes-at-runtime#964049 might work. If your code takes care of the rest, the user would only have to provide the function that is to become a method, not a whole class overriding the old one. – das-g Mar 06 '16 at 23:09

1 Answers1

1

You can dynamically add or replace methods of a class by assigning functions as unbound methods. For example:

class Foo(object):
    pass

f = Foo()

def m(self, x):
    self.x = x

Foo.method = m

f.method(123)

print(f.x)

This prints 123. Even though method wasn't added until after f was created, it is still callable from f.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41