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:
- Decorators
- Metaclasses (`type`)
- Dynamic attribute binding (
[[__builtins__/getattr|getattr]],[[__builtins__/setattr|setattr]],[[__builtins__/delattr|delattr]]) - Dynamic code execution (
[[__builtins__/exec|exec()]],[[__builtins__/eval|eval()]],[[__builtins__/compile|compile()]])
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
- tuts/python3 Linked here; links to this page
- tuts/python3/python decorators Linked here; links to this page
- tuts/python3/tutorials/advanced_python_internals/python_object_mro_and_initialization Linked here; links to this page
- tuts/python3/__builtins__ Linked here
- tuts/python3/__builtins__/exec Linked here
- tuts/python3/__builtins__/setattr Linked here
- tuts/python3/__builtins__/super Linked here
- tuts/python3/__builtins__/type Linked here
- tuts/python3/tutorials links to this page
- tuts/python3/tutorials/advanced_python_internals links to this page