On this page
  1. python metaprogramming
  2. Overview
  3. Dynamic Method Binding (setattr)

python metaprogramming

Prev: python decorators | Up: python3 | Next: __builtins__
Rel: python3, python decorators, Python Object, MRO & Initialization Dunder Flow, type, setattr, exec, super
Ref: docs.python.org — Data Model & Metaclasses
Tags: #public #python3 #metaprogramming


Overview

Metaprogramming refers to code that inspects or modifies classes, methods, or code at runtime using:


Dynamic Method Binding (setattr)

class A:
    def func(self):
        print('func derived from A')

class B:
    def func(self):
        print('func derived from B')

class C(B, A):
    def __init__(self):
        super().__init__()

def change_method_name(cls, name):
    def method(self):
        print('func from changed_func')
    method.__name__ = name
    return setattr(cls, name, method)

change_method_name(A, 'changed_func')
a = A()
a.changed_func()

Linked from

Related notes