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 type
1class Meta(type):
# __new__ is called when creating a new class
2 def __new__(mcs, name, bases, namespace):
# Add version attribute to the class namespace
3 namespace['version'] = '1.0'
# Call parent __new__ to create the class
4 return super().__new__(mcs, name, bases, namespace)
5
# Create class using the metaclass
6class MyClass(metaclass=Meta):
# Empty class body
7 pass
8
# Print the automatically added version attribute
9print(MyClass.version)
# Print the type of MyClass which is Meta
10print(type(MyClass))

Output

1.0
<class '__main__.Meta'>
Practice typing this code

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

More Python examples at level 5

← Python typing practice