Metaclass Definition in Python
Level 5222 keystrokes
This creates a metaclass that modifies class creation. The metaclass adds attributes to classes automatically during definition.
Python code
# Define metaclass inheriting from type1class Meta(type): # __new__ is called when creating a new class2 def __new__(mcs, name, bases, namespace): # Add version attribute to the class namespace3 namespace['version'] = '1.0' # Call parent __new__ to create the class4 return super().__new__(mcs, name, bases, namespace)5 # Create class using the metaclass6class MyClass(metaclass=Meta): # Empty class body7 pass8 # Print the automatically added version attribute9print(MyClass.version)# Print the type of MyClass which is Meta10print(type(MyClass))Output
1.0 <class '__main__.Meta'>
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 8(× 8)× 8,× 6'× 4:× 3.× 3=× 2[× 1]× 1