Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Challenge: Required Method Enforcement | Custom Metaclasses in Action
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
Python Metaclasses Demystified
Section 2. Chapitre 6
single

single

bookChallenge: Required Method Enforcement

Glissez pour afficher le menu

As you have seen in previous chapters, metaclasses allow you to intercept and customize class creation in Python. One of the most powerful patterns is validation: using the metaclass to enforce certain rules or requirements on classes at the time they are defined. This could include checking for required attributes, ensuring naming conventions, or validating the presence of specific methods. By leveraging the __new__ or __init__ methods of a metaclass, you can examine the class’s namespace and raise an error if requirements are not met. This pattern helps catch mistakes early and ensures that all classes using the metaclass follow the same contract.

Tâche

Swipe to start coding

Write a metaclass that enforces every class using it must define a callable method named describe. If the class does not define this method, the metaclass should raise a TypeError during class creation. The error message must use double quotes outside and single quotes inside the f-string. The message should follow this format: Class "ClassName" must define a callable 'describe' method.

  • Define a metaclass that checks for a callable method named describe in each class using it;
  • If the requirement is not met, raise a TypeError during class creation;
  • Use an error message like: Class "ClassName" must define a callable 'describe' method.

Solution

Switch to desktopPassez à un bureau pour une pratique réelleContinuez d'où vous êtes en utilisant l'une des options ci-dessous
Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 6
single

single

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

some-alt