Create Your First Metaclass

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Objectives:

  • Create your first metaclass

Files Created: mymeta.py


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ObjectOrientedProgrammingGroup -.-> python/classes_objects("`Classes and Objects`") python/ObjectOrientedProgrammingGroup -.-> python/constructor("`Constructor`") python/ObjectOrientedProgrammingGroup -.-> python/polymorphism("`Polymorphism`") python/ObjectOrientedProgrammingGroup -.-> python/encapsulation("`Encapsulation`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132519{{"`Create Your First Metaclass`"}} python/variables_data_types -.-> lab-132519{{"`Create Your First Metaclass`"}} python/lists -.-> lab-132519{{"`Create Your First Metaclass`"}} python/tuples -.-> lab-132519{{"`Create Your First Metaclass`"}} python/function_definition -.-> lab-132519{{"`Create Your First Metaclass`"}} python/classes_objects -.-> lab-132519{{"`Create Your First Metaclass`"}} python/constructor -.-> lab-132519{{"`Create Your First Metaclass`"}} python/polymorphism -.-> lab-132519{{"`Create Your First Metaclass`"}} python/encapsulation -.-> lab-132519{{"`Create Your First Metaclass`"}} python/data_collections -.-> lab-132519{{"`Create Your First Metaclass`"}} python/build_in_functions -.-> lab-132519{{"`Create Your First Metaclass`"}} end

Create your first metaclass

Create a file called mymeta.py and put the following code in it (from the slides):

## mymeta.py

class mytype(type):
    @staticmethod
    def __new__(meta, name, bases, __dict__):
        print("Creating class :", name)
        print("Base classes   :", bases)
        print("Attributes     :", list(__dict__))
        return super().__new__(meta, name, bases, __dict__)

class myobject(metaclass=mytype):
    pass

Once you've done this, define a class that inherits from myobject instead of object. For example:

class Stock(myobject):
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price
    def cost(self):
        return self.shares * self.price
    def sell(self, nshares):
        self.shares -= nshares

Try running your code and creating instances of Stock. See what happens. You should see the print statements from your mytype running once when the Stock class is defined.

What happens if you inherit from Stock?

class MyStock(Stock):
    pass

You should still see your metaclass at work. Metaclasses are "sticky" in that they get applied across an entire inheritance hierarchy.

Discussion

Why would you want to do something like this? The main power of a metaclass is that it gives a programmer the ability to capture details about classes just prior to their creation. For example, in the __new__() method, you are given all of the basic details including the name of the class, base classes, and methods data. If you inspect this data, you can perform various types of diagnostic checks. If you're more daring, you can modify the data and change what gets placed in the class definition when it is created. Needless to say, there are many opportunities for horrible diabolical evil.

Summary

Congratulations! You have completed the Create Your First Metaclass lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like