All Topics  
Metaclass

 

   Email Print
   Bookmark   Link






 

Metaclass



 
 
In object-oriented
Object-oriented programming

Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs....
 programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
, a metaclass is a class
Class (computer science)

In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
 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 support metaclasses. Among those which do, the extent to which metaclasses can override any given aspect of class behavior varies. Each language has its own metaobject protocol, a set of rules which govern how objects, classes, and metaclasses interact.

Python example
In Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
, the builtin class type is a metaclass.






Discussion
Ask a question about 'Metaclass'
Start a new discussion about 'Metaclass'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In object-oriented
Object-oriented programming

Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs....
 programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
, a metaclass is a class
Class (computer science)

In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
 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 support metaclasses. Among those which do, the extent to which metaclasses can override any given aspect of class behavior varies. Each language has its own metaobject protocol, a set of rules which govern how objects, classes, and metaclasses interact.

Python example


In Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
, the builtin class type is a metaclass. Consider this simple Python class:

class Car(object): __slots__ = ['make', 'model', 'year', 'color']

def __init__(self, make, model, year, color): self.make = make self.model = model self.year = year self.color = color

@property def description(self): """ Return a description of this car. """ return "%s %s %s %s" % (self.color, self.year, self.make, self.model)

At run time, Car itself is a type object. 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 in kwargs: setattr(obj, name, kwargs[name])

# 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. This is done in Python 2 by assigning to __metaclass__ within the class definition (in Python 3.0, you inherit from metaclass=M instead): class Car(object): __metaclass__ = AttributeInitType __slots__ = ['make', 'model', 'year', 'color']

@property def description(self): """ Return a description of this car. """ return "%s %s %s %s" % (self.color, self.year, self.make, self.model) Car objects can then be instantiated like this: cars = [ Car(make='Toyota', model='Prius', year=2005, color='green'), Car(make='Ford', model='Prefect', year=1979, color='blue')] Metaclass programming can be confusing, and it is rare in real-world Python code.

In Smalltalk-80


In Smalltalk
Smalltalk

Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al...
, everything is an object
Object (computer science)

In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably....
. There are two kinds of objects: those which can create instances of themselves (classes), and others which cannot. Every object is the instance of a class. Every class is the instance of a metaclass.

In early Smalltalks, there was one metaclass called Class. The object creation method
Method (computer science)

In object-oriented programming, a method is a subroutine that is exclusively associated either with a class or with an object . Like a procedure in procedural programming languages, a method usually consists of a sequence of statement to perform an action, a set of input parameter to customize those actions, and possibly an output value...
 of all classes was the same, i.e., new. A class sent the message new could only return an object with uninitialized instance variable
Instance variable

In object-oriented programming with Class es, an instance variable is a variable defined in a class, for which each object in the class has a separate copy....
s. Smalltalk's designers wanted to send one message to an object to initiate both creation and initializaton. They achieved this in Smalltalk-80.

In Smalltalk-80, a class is an instance of its own metaclass; and each class can have unique methods for creating objects. Metaclasses, like other classes, contain methods used by their instances. But metaclasses are all instances of one class, called Metaclass. Unlike classes, metaclasses do not need flexibile creation methods, because classes all have the same structure. For instance, the class Car has instance variables just like any other class. People using (and not re-designing) Smalltalk do not need to write class creation methods.

Names are not given to metaclasses. The metaclass of class Sphere is simply referred to as "the metaclass of class Sphere". The metaclass of a class may be accessed by sending the message class to the class.

The methods of a metaclass create instances, and initialize class variable
Class variable

In object-oriented programming with Class es, a class variable is a variable defined in a Class of which a single copy exists, regardless of how many objects of the class exist....
s.

In Smalltalk-80, every class (except Object) has a superclass
Superclass

Superclass may be:* The global ruling class created by globalization .* Superclass , a book about global governance by David Rothkopf.* Superclass , a taxonomic rank intermediate between subphylum and class....
. The abstract superclass 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

Conjoined twins are whose bodies are joined in utero. A rare phenomenon, the occurrence is estimated to range from 1 in 50,000 births to 1 in 200,000 births, with a somewhat higher incidence in Southwest Asia and Africa....
, classes and metaclasses are born together. Metaclass has an instance variable thisClass, which points to its conjoined class.

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 which provides common methods for all objects; "an object" is an integer, or a widget, or a Car, etc.


  • Class is the base metaclass which provides common methods for all classes; "a class" is something like Integer, or Widget, or Car, etc.


  • Metaclass has the same relation to "a Metaclass".


Four classes provide the facilities to describe new classes. Their inheritance hierarchy (from Object), and the main facilities they provide are:

Object - default behavior common to all objects, like class access
Behavior - minimum state
State

A state is a political Social contract with effective sovereignty over a geographic area and representing a population. These may be nation states, State or multinational states....
 for compiling methods and creating/running objects ClassDescription (abstract class) - class/variable naming, comments Class - similar, more comprehensive, facilities to superclasses Metaclass - initializing class variables, instance creation messages + read on...

Class methods 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 not found it proceeds up the superclass chain, stopping at Object whether it is found or not.

Aside - another way of saying "metaclass of Integer" is Integer class.

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.

All metaclasses are instances of class Metaclass. So the metaclass of Metaclass is an instance of Metaclass.

Support in languages and tools



The following programming language
Programming language

A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer....
s support metaclasses.
  • Common Lisp
    Common Lisp

    Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
    , via CLOS
  • Groovy
  • Object Pascal
    Object Pascal

    Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi....
     (especially in CodeGear Delphi)
  • Objective-C
    Objective-C

    Objective-C is a Reflection , Object-oriented programming programming language which adds Smalltalk-style message passing to C .Today it is used primarily on Mac OS X, iPhone OS, and GNUstep, three environments based on the OpenStep standard, and is the primary language used for the NEXTSTEP, OpenStep#OPENSTEP, and Cocoa application framew...
  • Python
    Python (programming language)

    Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
  • Perl
    Perl

    In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
    , via the metaclass pragma
  • Ruby
    Ruby (programming language)

    Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
     (follows the same scheme as Smalltalk )
  • Smalltalk
    Smalltalk

    Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al...


Some less widespread languages which support metaclasses include OpenJava
OpenJava

OpenJava is a programming tool that parses and analyzes Java source code. It uses a metaobject protocol to provide services for language extensions....
, OpenC++, OpenAda, CorbaScript
CorbaScript

CorbaScript is an object-oriented scripting language.See also*CORBA*CorbaWebExternal links** ITworld* by Christophe Gransart...
, ObjVLisp
ObjVlisp

ObjVlisp is a 1984 object-oriented extension of Vlisp with a Reflection architecture.["Metaclasses are First Class: The ObjVlisp Model", P. Cointe, SIGPLAN Notices 22:156-167 ]....
, Object-Z
Object-Z

Object-Z is an object-oriented extension to Z specification language developed at the University of Queensland, Australia.Object-Z extends Z by the addition of language constructs resembling the object-oriented paradigm, most notably, Class ....
, MODEL-K, XOTcl
XOTcl

XOTcl is an object-oriented extension for the Tcl created by G. Neumann and U. Zdun. It supports metaclasses. Class and Method definitions are completely dynamic....
, and MELDC. Several of these languages date from the early 1990s and are of academic interest.

Logtalk
Logtalk

Logtalk is an open source Object-oriented programming logic programming language that can use most Prolog implementations as a back-end compiler....
, an object-oriented extension of Prolog
Prolog

Prolog is a logic programming language. It is a general purpose language often associated with artificial intelligence and computational linguistics....
, also supports metaclasses.

Resource Description Framework
Resource Description Framework

The Resource Description Framework is a family of World Wide Web Consortium specifications originally designed as a metadata data model. It has come to be used as a general method for conceptual description or modeling, of information that is implemented in web resources; using a variety of syntax formats....
 (RDF) and Unified Modeling Language
Unified Modeling Language

Unified Modeling Language is a standardized general-purpose modeling language in the field of software engineering.UML includes a set of graphical notation techniques to create abstract models of specific systems....
 (UML) both support metaclasses.

See also

  • Metamodel
  • Metaprogramming
    Metaprogramming

    Metaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at runtime that would otherwise be done at compile time....
  • Metaobject protocol (MOP)
  • Reflection
    Reflection (computer science)

    In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming....
  • Dynamism
    Dynamism

    Dynamism is a concept that has several meanings.*Dynamism , a cosmological explanation of the material world in the vein of process philosophy....
  • Adapter pattern
    Adapter pattern

    In computer programming, the adapter design pattern translates one Interface for a Class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface....


External links

  • IBM Metaclass programming in Python, parts , and
  • Artima Forum: Metaclasses in Python 3.0


Further reading

  • Ira R. Forman and Scott Danforth, Putting Metaclasses to Work (1999), ISBN 0-201-43305-2