Skip to content

Instantly share code, notes, and snippets.

@samukasmk
Created January 30, 2025 15:22
Show Gist options
  • Save samukasmk/303bd38a1efa68744237f4680d9d0b91 to your computer and use it in GitHub Desktop.
Save samukasmk/303bd38a1efa68744237f4680d9d0b91 to your computer and use it in GitHub Desktop.
Example of dynamic class inheritance in Python
class Parent1:
def parent1_method(self):
return "Method from Parent1 class"
class Parent2:
def parent2_method(self):
return "Method from Parent2 class"
class Child:
def __init__(self, parent_class):
# Dynamically creating a new class with the desired inheritance
self.__class__ = type(self.__class__.__name__, (parent_class,), dict(self.__class__.__dict__))
if __name__ == '__main__':
# Testing with Parent1
obj1 = Child(Parent1)
print(obj1.parent1_method()) # "Method from Parent1 class"
# Testing with Parent2
obj2 = Child(Parent2)
print(obj2.parent2_method()) # "Method from Parent2 class"
"""
$ python dynamic_inheritance.py
Method from Parent1 class
Method from Parent2 class
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment