Python Class Patching



About

Classes in python are objects and very modifiable in various ways - metaclasses, decorators, runtime patching.

Runtime Method Patching

  • Blog Tutorial - replacing class methods after instantiation and how to take care of which self is used to access internal variables.
  • StackOverflow Example - how to add, and delete methods (i.e. not replace)

Some important points:

  1. Simply replacing a method with a member method from another class will divert you to the other class's internal variables when you call self.xxx.
  2. You can use types.MethodType to bind an arbitrarily defined function with a self arg to a class member method.



Class Decorators

MetaClasses