class — Expert Examples
Defines a new class (blueprint for creating objects)
Metaclasses: classes that create classes
Using a metaclass to customize class creation.
python
class ValidatedMeta(type): def __new__(mcs, name, bases, namespace): # Require all public methods to have docstrings for key, value in namespace.items(): if callable(value) and not key.startswith("_"): if not getattr(value, "__doc__", None): raise TypeError( f"{name}.{key}() must have a docstring" ) return super().__new__(mcs, name, bases, namespace) class API(metaclass=ValidatedMeta): def get_users(self): """Fetch all users.""" return [] def get_orders(self): """Fetch all orders.""" return [] print(f"API created with metaclass: {type(API)}") print(f"Methods: {[m for m in dir(API) if not m.startswith('_')]}") try: class BadAPI(metaclass=ValidatedMeta): def no_docs(self): # missing docstring pass except TypeError as e: print(f"Metaclass rejected: {e}")
Metaclasses control how classes themselves are created. type is the default metaclass. Custom metaclasses can enforce coding standards, register classes, or inject behavior at class definition time.
Want to try these examples interactively?
Open Expert Playground