Editor

Create a Class with type()

Advanced · Write the code · from Python Metaclasses: Control How Classes Are Created

From the lesson: Python Metaclasses: Control How Classes Are Created

You already know that classes create objects. But have you ever wondered - what creates the classes themselves? In Python, the answer is metaclasses.

Read the lesson

Use the type() function (not a class statement) to create a class called Counter with:

  • An attribute count initialized to 0
  • A method increment(self) that increases count by 1 and returns the new value
  • Then create an instance, call increment() three times, and print the final count.

    # Create the Counter class using type()
    # Then create an instance and call increment() 3 times

    More Metaclass exercises

    All Python exercises · 50 practice problems · Metaprogramming quiz