Skip to main content

Metaclass (Computer Science)

A Metaclass in Object-oriented programming is a class whose instances contain class-definitions. Metaclasses can be used to define behavior and attributes of classes.

Python Example

In Python, classes are objects that can be used to construct instances.

"Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state."

Employee Example

class Employee: pass

The metaclass of Employee is type:

print(type(Employee)); # <class 'type'>

Employee is now a First Class Citizen:

  • it can be assigned to other variables: EmployeeFactory = Employee
  • it be passed to other methods as an argument: print(Employee)

Additionally, properties can be added during runtime: Employee.prop = "value";

Calling Employee as a method will create an instance of Employee:

emp = Employee();
print(type(emp)); # <class '__main__.Employee'>
In a nutshell
  • type is the Metaclass of Employee.
  • thus, Employee is an instance of type.
  • calling Employee() creates and returns an instance of Employee.

See also