WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Intermediate · question 35 of 100

What is the concept of a metaclass in Python? Can you provide a simple example?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

In Python, a metaclass is a class that defines the behavior of other classes. A metaclass is used to create new classes, just as a class is used to create new objects. Metaclasses provide a way to customize the behavior of classes and add additional functionality to them.

In Python, the built-in type function is a metaclass. When you define a new class, the type function is used to create a new class object. You can define your own metaclass by creating a new class that inherits from type and customizing its behavior.

Here is a simple example of how to create a metaclass in Python:

    class MyMetaclass(type):
    def __new__(cls, name, bases, attrs):
        # modify the attributes of the new class
        attrs['greeting'] = 'Hello, world!'
        
        # create the new class object using the parent __new__ method
        return super().__new__(cls, name, bases, attrs)
    
    class MyClass(metaclass=MyMetaclass):
        pass
    
    print(MyClass.greeting)

In this example, MyMetaclass is a custom metaclass that modifies the attributes of any new class that uses it as a metaclass. The __new__ method is called when a new class is created, and it modifies the attrs dictionary to add a new attribute called greeting with the value ’Hello, world!’.

The MyClass class is defined with the metaclass parameter set to MyMetaclass, which tells Python to use MyMetaclass as the metaclass for MyClass. When MyClass is created, the __new__ method of MyMetaclass is called to modify the class attributes.

Finally, the greeting attribute of MyClass is printed, which should output ’Hello, world!’.

In summary, a metaclass is a class that defines the behavior of other classes in Python. Metaclasses provide a way to customize the behavior of classes and add additional functionality to them. A metaclass is defined by creating a new class that inherits from type and customizing its behavior, such as modifying the attributes of any new class that uses it as a metaclass.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics