Senior LevelPython
How do you dynamically generate ORM models or API serializers at runtime using the 3-argument type(name, bases, dict) constructor?
❓ Interview Prompt: Explain Metaclasses, dynamic class creation using `type('Name', (Bases,), {attributes})`, and runtime code generation.
In Python, classes are instances of the metaclass 'type'. You can dynamically instantiate new classes at runtime using the 3-argument 'type(name, bases, dict)' constructor:
Parameters:
1
'name': String name of the new class.
2
'bases': Tuple of parent classes to inherit from.
3
'dict': Dictionary mapping class attribute names to values and functions.
Code Implementation Example
python
# Dynamically construct a new class at runtime!
DynamicUserModel = type(
'DynamicUserModel',
(object,), # Base classes tuple
{
'role': 'ADMIN',
'get_role': lambda self: self.role
}
)
instance = DynamicUserModel()
print(instance.get_role()) # 'ADMIN'💡Dynamically constructing classes at runtime using the 3-argument type() constructor.
🎯 Interview Key Takeaway
Use the 3-argument type() constructor to dynamically generate classes at runtime for ORM schemas and dynamic serializers.
#metaclass#type()#Dynamic Classes#Metaprogramming#Senior
Back to all Python Questions→