In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
, a metaclass is a
class
Class or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used differentl ...
whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented
programming languages
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
support metaclasses. Among those that do, the extent to which metaclasses can override any given aspect of class behavior varies. Metaclasses can be implemented by having classes be
first-class citizens, in which case a metaclass is simply an object that constructs classes. Each language has its own
metaobject protocol, a set of rules that govern how objects, classes, and metaclasses interact.
Python example
In
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
, the builtin class
type
is a metaclass. Consider this simple Python class:
class Car:
def __init__(self, make: str, model: str, year: int, color: str):
self.make = make
self.model = model
self.year = year
self.color = color
@property
def description(self) -> str:
"""Return a description of this car."""
return f" "
At run time,
Car
itself is an instance of
type
. The source code of the
Car
class, shown above, does not include such details as the size in bytes of
Car
objects, their binary layout in memory, how they are allocated, that the
__init__
method is automatically called each time a
Car
is created, and so on. These details come into play not only when a new
Car
object is created, but also each time any attribute of a
Car
is accessed. In languages without metaclasses, these details are defined by the language specification and can't be overridden. In Python, the metaclass -
type
- controls these details of
Car
's behavior. They can be overridden by using a different metaclass instead of
type
.
The above example contains some redundant code to do with the four attributes
make
,
model
,
year
, and
color
. It is possible to eliminate some of this redundancy using a metaclass. In Python, a metaclass is most easily defined as a subclass of
type
.
class AttributeInitType(type):
def __call__(self, *args, **kwargs):
"""Create a new instance."""
# First, create the object in the normal default way.
obj = type.__call__(self, *args)
# Additionally, set attributes on the new object.
for name, value in kwargs.items():
setattr(obj, name, value)
# Return the new object.
return obj
This metaclass only overrides object creation. All other aspects of class and object behavior are still handled by
type
.
Now the class
Car
can be rewritten to use this metaclass. In Python 3 this is done by providing a "keyword argument"
metaclass
to the class definition:
class Car(object, metaclass=AttributeInitType):
@property
def description(self) -> str:
"""Return a description of this car."""
return " ".join(str(value) for value in self.__dict__.values())
The resulting object
Car
can be instantiated as usual, but can contain any number of keyword arguments:
new_car = Car(make='Toyota', model='Prius', year=2005, color='Green', engine='Hybrid')
In Smalltalk-80
![Smalltalk metaclass](https://upload.wikimedia.org/wikipedia/commons/9/93/Smalltalk_metaclass.png)
In
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
, everything is an
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
. Additionally, Smalltalk is a
class based system, which means that every object has a class that defines the structure of that object (i.e. the instance variables the object has) and the messages an object understands. Together this implies that a class in Smalltalk is an object and that, therefore a class needs to be an instance of a class (called metaclass).
As an example, a car object
c
is an instance of the class
Car
. In turn, the class
Car
is again an object and as such an instance of the metaclass of
Car
called
Car class
. Note the blank in the name of the metaclass. The name of the metaclass is the Smalltalk expression that, when evaluated, results in the metaclass object. Thus evaluating
Car class
results in the metaclass object for
Car
whose name is
Car class
(one can confirm this by evaluating
Car class name
which returns the name of the metaclass of
Car
.)
Class method
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
s actually belong to the metaclass, just as instance methods actually belong to the class. When a message is sent to the object
2
, the search for the method starts in
Integer
. If it is not found it proceeds up the superclass chain, stopping at Object whether it is found or not.
When a message is sent to
Integer
the search for the method starts in
Integer class
and proceeds up the superclass chain to
Object class
. Note that, so far, the metaclass inheritance chain exactly follows that of the class inheritance chain. But the metaclass chain extends further because
Object class
is the subclass of
Class
. All metaclasses are subclasses of Class.
In early Smalltalks, there was only one metaclass called
Class
. This implied that the
methods
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
all classes have were the same, in particular the method to create new objects, i.e.,
new
. To allow classes to have their own methods and their own instance variables (called class instance variables and should not be confused with
class variable
In class-based, object-oriented programming, a class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist.
A class variable is not an instance variable. It is a special typ ...
s), Smalltalk-80 introduced for each class
C
their own metaclass
C class
. This means that each metaclass is effectively a
singleton
Singleton may refer to:
Sciences, technology Mathematics
* Singleton (mathematics), a set with exactly one element
* Singleton field, used in conformal field theory Computing
* Singleton pattern, a design pattern that allows only one instance ...
class.
Since there is no requirement that metaclasses behave differently from each other, all metaclasses are instances of only one class called
Metaclass
. The metaclass of
Metaclass
is called
Metaclass class
which again is an instance of class
Metaclass
.
In Smalltalk-80, every class (except
Object
) has a
superclass. The
abstract superclass
In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). In many languages, the class n ...
of all metaclasses is
Class
, which describes the general nature of classes.
The superclass hierarchy for metaclasses parallels that for classes, except for class
Object
. ALL metaclasses are subclasses of
Class
, therefore:
*
Object class superclass Class.
Like
conjoined twins
Conjoined twins – sometimes popularly referred to as Siamese twins – are twins joined ''Uterus, in utero''. A very rare phenomenon, the occurrence is estimated to range from 1 in 49,000 births to 1 in 189,000 births, with a somewhat higher in ...
, classes and metaclasses are born together.
Metaclass
has an instance variable
thisClass
, which points to its conjoined class.
Note that the usual Smalltalk
class browser
{{Unreferenced, date=July 2010
A class browser is a feature of an integrated development environment (IDE) that allows the programmer to browse, navigate, or visualize the structure of object-oriented programming code.
History
Most modern clas ...
does not show metaclasses as separate classes. Instead the class browser allows to edit the class together with its metaclass at the same time.
The names of classes in the metaclass hierarchy are easily confused with the concepts of the same name. For instance:
*
Object
is the base class that provides common methods for all objects; "an object" is an integer, or a widget, or a
Car
, etc.
*
Class
is the base of the metaclasses that provides common methods for all classes (though it is not a metaclass itself); "a class" is something like
Integer
, or
Widget
, or
Car
, etc.
*
Metaclass
provides common methods for all metaclasses.
Four classes provide the facilities to describe new classes. Their
inheritance hierarchy
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
(from Object), and the main facilities they provide are:
:Object - default behavior common to all objects, like class access
::Behavior - minimum
state
State may refer to:
Arts, entertainment, and media Literature
* ''State Magazine'', a monthly magazine published by the U.S. Department of State
* ''The State'' (newspaper), a daily newspaper in Columbia, South Carolina, United States
* ''Our S ...
for
compiling
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
methods and creating/running objects
:::ClassDescription (
abstract class
In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Every instance of an abstra ...
) - class/variable naming, comments
::::Class - similar, more comprehensive, facilities to superclasses
::::Metaclass - initializing class variables, instance creation messages
In Ruby
Ruby purifies the Smalltalk-80 concept of metaclasses by introducing
eigenclasses,
removing the
Metaclass
class,
and (un)redefining the class-of map.
The change can be schematized as follows:
Note in particular the correspondence between Smalltalk's implicit metaclasses and Ruby's eigenclasses of classes.
The Ruby eigenclass model makes the concept of implicit metaclasses fully uniform: every object ''x'' has its own meta-object, called the ''eigenclass'' of ''x'', which is one meta-level higher than ''x''. The "higher order" eigenclasses usually exist purely conceptually – they do not contain any methods or store any (other) data in most Ruby programs.
The following diagrams show a sample core structure of Smalltalk-80 and Ruby in comparison.
In both languages, the structure consists of a built-in part which contains the circular objects (i.e. objects that appear in a cycle formed by a combination of blue or green links) and a user-part which has four explicit objects: classes
A
and
B
and terminal objects
u
and
v
.
Green links show the child→parent relation of inheritance (with the implicit upward direction), blue links show the complementary member→container relation of instantiation (a blue link from ''x'' points to the least actual container of ''x'' that is the start point for the method lookup when a method is invoked on ''x''). Gray nodes display the eigenclasses (resp. implicit metaclasses in the case of Smalltalk-80).
The diagram on the right also provides a picture of
lazy evaluation
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).
The b ...
of eigenclasses in Ruby. The
v
object can have its eigenclass evaluated (allocated) as a consequence of adding ''singleton methods'' to
v
.
According to the Ruby's introspection method named
class
,
the class of every class (and of every eigenclass) is
constantly the
Class
class (denoted by
c
in the diagram).
Class
, and
Struct
are the only classes that have classes as instances. Subclassing of
Class
is disallowed.
Following the standard definition of metaclasses we can conclude that
Class
and
Struct
are the only metaclasses in Ruby.
This seems to contradict the correspondence between Ruby and Smalltalk,
since in Smalltalk-80, every class has its own metaclass.
The discrepancy is based on the disagreement between
the
class
introspection method in Ruby and Smalltalk. While the map ''x ↦ x.''
class
coincides on terminal objects, it differs in the restriction to classes. As already mentioned above, for a class
''x''
, the Ruby expression
''x''.class
evaluates constantly to
Class
. In Smalltalk-80, if
''x''
is a class then the expression
''x'' class
corresponds
to the Ruby's
''x''.singleton_class
– which evaluates to the eigenclass of
''x''
.
In Objective-C
![Objective-C metaclass](https://upload.wikimedia.org/wikipedia/commons/5/5e/Objective-C_metaclass.png)
Metaclasses in Objective-C are almost the same as those in Smalltalk-80—not surprising since Objective-C borrows a lot from Smalltalk. Like Smalltalk, in Objective-C, the instance variables and methods are defined by an object's class. A class is an object, hence it is an instance of a metaclass.
Like Smalltalk, in Objective-C, class methods are simply methods called on the class object, hence a class's class methods must be defined as instance methods in its metaclass. Because different classes can have different sets of class methods, each class must have its own separate metaclass. Classes and metaclasses are always created as a pair: the runtime has functions
objc_allocateClassPair()
and
objc_registerClassPair()
to create and register class-metaclass pairs, respectively.
There are no names for the metaclasses; however, a pointer to any class object can be referred to with the generic type
Class
(similar to the type
id
being used for a pointer to any object).
Because class methods are inherited through inheritance, like Smalltalk, metaclasses must follow an inheritance scheme paralleling that of classes (e.g. if class A's parent class is class B, then A's metaclass's parent class is B's metaclass), except that of the root class.
Unlike Smalltalk, the metaclass of the root class inherits from the root class (usually
NSObject
using the
Cocoa
Cocoa may refer to:
Chocolate
* Chocolate
* ''Theobroma cacao'', the cocoa tree
* Cocoa bean, seed of ''Theobroma cacao''
* Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter and ...
framework) itself. This ensures that all class objects are ultimately instances of the root class, so that you can use the instance methods of the root class, usually useful utility methods for objects, on class objects themselves.
Since metaclass objects do not behave differently (you cannot add class methods for a metaclass, so metaclass objects all have the same methods), they are all instances of the same class—the metaclass of the root class (unlike Smalltalk). Thus, the metaclass of the root class is an instance of itself. The reason for this is that all metaclasses inherit from root class; hence, they must inherit the class methods of the root class.
Support in languages and tools
The following are some of the most prominent
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s that support metaclasses.
*
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
, via
CLOS
Clos may refer to:
People
* Clos (surname)
Other uses
* CLOS, Command line-of-sight, a method of guiding a missile to its intended target
* Clos network, a kind of multistage switching network
* Clos (vineyard), a walled vineyard; used in Fran ...
*
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracle ...
and other versions of
Object Pascal
Object Pascal is an extension to the programming language Pascal (programming language), Pascal that provides object-oriented programming (OOP) features such as Class (computer programming), classes and Method (computer programming), methods.
...
influenced by it
*
Groovy
''Groovy'' (or, less commonly, ''groovie'' or ''groovey'') is a slang colloquialism popular during the 1950s, '60s and '70s. It is roughly synonymous with words such as "excellent", "fashionable", or "amazing", depending on context.
History
The ...
*
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
*
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
*
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
, via the metaclass pragma, as well as
Moose
The moose (in North America) or elk (in Eurasia) (''Alces alces'') is a member of the New World deer subfamily and is the only species in the genus ''Alces''. It is the largest and heaviest extant species in the deer family. Most adult mal ...
*
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
*
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Ka ...
*
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
(planned for
C++23 C23 or C-23 may refer to:
Vehicles
;Aircraft
* Beechcraft C23 Musketeer, an American civil utility aircraft
* Caspar C 23, a German sport aircraft
* Caudron C.23, a French bomber biplane
* Lockheed C-23 Altair, an American military transport
* S ...
)
Some less widespread languages that support metaclasses include
OpenJava,
OpenC++,
OpenAda,
CorbaScript,
ObjVLisp,
Object-Z,
MODEL-K,
XOTcl
XOTcl is an object-oriented extension for the Tcl, Tool Command Language created by Gustaf Neumann and Uwe Zdun. It is a derivative of MIT OTcl. XOTcl is based on a dynamic object system with metaclasses which as influenced by CLOS. Class (compute ...
, and
MELDC. Several of these languages date from the early 1990s and are of academic interest.
Logtalk
Logtalk is an object-oriented logic programming language that extends and leverages the Prolog language with a feature set suitable for programming in the large.Paulo Moura (2003). Logtalk: Design of an Object-Oriented Logic Programming Language. ...
, an object-oriented extension of
Prolog
Prolog is a logic programming language associated with artificial intelligence and computational linguistics.
Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
, also supports metaclasses.
Resource Description Framework The Resource Description Framework (RDF) is a World Wide Web Consortium (W3C) standard originally designed as a data model for metadata. It has come to be used as a general method for description and exchange of graph data. RDF provides a variety of ...
(RDF) and
Unified Modeling Language
The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
The creation of UML was originally m ...
(UML) both support metaclasses.
See also
*
Metamodel
A metamodel or surrogate model is a model of a model, and metamodeling is the process of generating such metamodels. Thus metamodeling or meta-modeling is the analysis, construction and development of the frames, rules, constraints, models and ...
*
Metaprogramming
Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. It means that a program can be designed to read, generate, analyze or transform other programs, and even modify itself ...
*
Metaobject In computer science, a metaobject is an object that manipulates, creates, describes, or implements objects (including itself). The object that the metaobject pertains to is called the base object. Some information that a metaobject might define incl ...
*
Kind (type theory) In the area of mathematical logic and computer science known as type theory, a kind is the type of a type constructor or, less commonly, the type of a higher-order type operator. A kind system is essentially a simply typed lambda calculus "one le ...
*
Reflection Reflection or reflexion may refer to:
Science and technology
* Reflection (physics), a common wave phenomenon
** Specular reflection, reflection from a smooth surface
*** Mirror image, a reflection in a mirror or in water
** Signal reflection, in ...
*
Dynamism
*
Adapter pattern
In software engineering, the adapter pattern is a software design pattern (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interface of an existing class to be used as another interface. It is often ...
*
Metaclass (Semantic Web)
What Is a Metaclass?
References
{{Data types
Class (computer programming)
Articles with example Python (programming language) code