tgoop.com/DataScienceQ/454
Create:
Last Update:
Last Update:
How to Dynamically Create a Class at Runtime in Python?
You can dynamically create a class in Python using the built-in type()
function. This is one of the simplest ways to leverage metaclasses.
Example:
# Create a new class dynamically
MyDynamicClass = type('MyDynamicClass', (object,), {
'say_hello': lambda self: print("Hello!")
})
# Use the dynamically created class
obj = MyDynamicClass()
obj.say_hello()
Explanation:
*
'MyDynamicClass'
: Name of the new class*
(object,)
: Tuple of base classes (here, just inheriting from object
)*
{'say_hello': ...}
: Dictionary of attributes/methods for the classOutput:
Hello!
This is a powerful feature used in metaprogramming and framework design.
#PythonTips #Metaclass #PythonOOP #DynamicClass #typeFunction #AdvancedPython #CodingTips
🌺https://www.tgoop.com/DataScienceQ
BY Python & Data Science Questions, Answers, Quizzes, Interviews
Share with your friend now:
tgoop.com/DataScienceQ/454