Custom functionality with metaclasses

suggest change

Functionality in metaclasses can be changed so that whenever a class is built, a string is printed to standard output, or an exception is thrown. This metaclass will print the name of the class being built.

class VerboseMetaclass(type):

    def __new__(cls, class_name, class_parents, class_dict):
        print("Creating class ", class_name)
        new_class = super().__new__(cls, class_name, class_parents, class_dict)
        return new_class

You can use the metaclass like so:

class Spam(metaclass=VerboseMetaclass):
    def eggs(self):
        print("[insert example string here]")
s = Spam()
s.eggs()

The standard output will be:

Creating class Spam
[insert example string here]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents