Skip to content

Instantly share code, notes, and snippets.

@matbun
Created August 11, 2023 13:29
Show Gist options
  • Save matbun/a7e5bb8312dbc243318cb5b8704046de to your computer and use it in GitHub Desktop.
Save matbun/a7e5bb8312dbc243318cb5b8704046de to your computer and use it in GitHub Desktop.
Python - Add methods dynamically to a class (from another class)
"""MethodType for dynamic appending methods to classes"""
from types import MethodType
class A:
def __init__(self) -> None:
self.n = 0
def inc(self):
self.n += 1
def propagate_inc(self, class_instance):
class_instance.inc = MethodType(A.inc, class_instance)
class B:
def __init__(self) -> None:
self.n = 0
if __name__ == '__main__':
a = A()
print(f'A(n) {a.n}')
a.inc()
print(f'A(n) {a.n}')
b = B()
print(f'B(n) {b.n}')
a.propagate_inc(b)
b.inc()
print('inc?')
print(f'A(n) {a.n}')
print(f'B(n) {b.n}')
b.inc()
print(f'A(n) {a.n}')
print(f'B(n) {b.n}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment