Metaclass
Encyclopedia
In object-oriented
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 programming
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...

, a metaclass is a class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

 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 that 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 that govern how objects, classes, and metaclasses interact.

Python example

In Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its 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 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. This is done in Python 2 by assigning to __metaclass__ within the class definition (in Python 3 you provide a named argument, metaclass=M to the class definition 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')]

In Smalltalk-80

In Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective 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...

, everything is an object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

. Additionally, Smalltalk is a class based
Class-based programming
Class-based programming, or more commonly class-orientation, refers to the style of object-oriented programming in which inheritance is achieved by defining classes of objects, as opposed to the objects themselves .The most popular and developed model of OOP is a class-based model, as opposed to an...

 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 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 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 (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

 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
Class variable
In object-oriented programming with classes, 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 the opposite of an instance variable...

s), Smalltalk-80 introduced for each class C their own metaclass C class. This means that each metaclass is effectively a singleton 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
Superclass
Superclass may be:* The global ruling class created by neoliberal globalization * Superclass , a book about global governance by David Rothkopf, and The Superclass List...

. 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 identical twins whose bodies are joined in utero. A rare phenomenon, the occurrence is estimated to range from 1 in 50,000 births to 1 in 100,000 births, with a somewhat higher incidence in Southwest Asia and Africa. Approximately half are stillborn, and a smaller fraction of...

, 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
Class browser
A class browser is a feature of an integrated development environment that allows the programmer to browse, navigate, or visualize the structure of object-oriented programming code.- History :...

 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 metaclass that 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 (computer science)
In computer science and automata theory, a state is a unique configuration of information in a program or machine. It is a concept that occasionally extends into some forms of systems programming such as lexers and parsers....

 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

In Objective-C
The following information is accurate for the Cocoa
Cocoa (API)
Cocoa is Apple's native object-oriented application programming interface for the Mac OS X operating system and—along with the Cocoa Touch extension for gesture recognition and animation—for applications for the iOS operating system, used on Apple devices such as the iPhone, the iPod Touch, and...

 framework.


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 itself. (The root class is usually NSObject in Cocoa.) 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
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

s that support metaclasses.
  • Common Lisp
    Common Lisp
    Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

    , via CLOS
  • Delphi and most versions of Object Pascal
    Object Pascal
    Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...

  • Groovy
  • Objective-C
    Objective-C
    Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

  • Python
    Python (programming language)
    Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

  • Perl
    Perl
    Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

    , via the metaclass pragma, as well as Moose
    Moose (Perl)
    Moose is an extension of the Perl 5 object system. It brings modern object-oriented language features to Perl 5, making object-oriented programming more consistent and less tedious.-Features:...

  • Ruby
    Ruby (programming language)
    Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

  • Smalltalk
    Smalltalk
    Smalltalk is an object-oriented, dynamically typed, reflective 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...


Some less widespread languages that 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. Michiaki Tatsubori was the lead developer of OpenJava...

, OpenC++
OpenC++
OpenC++ is a software tool to parse and analyze C++ source code. It uses a metaobject protocol to provide services for language extensions. OpenC++ got its continuation in VivaCore library .-External links:**"" by Shigeru Chiba...

, OpenAda, CorbaScript
CorbaScript
CorbaScript is an object-oriented scripting language.-External links:*** ITworld* by Christophe Gransart...

, ObjVLisp
ObjVlisp
ObjVlisp is a 1984 object-oriented extension of Vlisp with a Reflective 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 the Z notation developed at the University of Queensland, Australia.Object-Z extends Z by the addition of language constructs resembling the object-oriented paradigm, most notably, classes...

, MODEL-K, XOTcl
XOTcl
XOTcl is an object-oriented extension for the Tool Command Language created by Gustaf Neumann and Uwe Zdun. It is an extension of the MIT OTcl. XOTcl 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 object-oriented logic programming language that extends the Prolog language with a feature set suitable for programming in the large. It provides support for encapsulation and data hiding, separation of concerns and enhanced code reuse...

, an object-oriented extension of Prolog
Prolog
Prolog is a general purpose 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 declarative: the program logic is expressed in terms of...

, 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...

 (RDF) and Unified Modeling Language
Unified Modeling Language
Unified Modeling Language is a standardized general-purpose modeling language in the field of object-oriented software engineering. The standard is managed, and was created, by the Object Management Group...

 (UML) both support metaclasses.
See also
  • Metamodel
    Metamodeling
    Metamodeling, or meta-modeling in software engineering and systems engineering among other disciplines, is the analysis, construction and development of the frames, rules, constraints, models and theories applicable and useful for modeling a predefined class of problems...

  • 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 compile time that would otherwise be done at runtime...

  • Metaobject
    Metaobject
    In computer science, a metaobject or meta-object is any entity that manipulates, creates, describes, or implements other objects. The object that the metaobject is about is called the base object...

  • Reflection
    Reflection (computer science)
    In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....

  • Dynamism
    Dynamism
    Dynamism is a concept that has several meanings.*Dynamism , a cosmological explanation of the material world in the vein of process philosophy.*Dynamism , a Japanese retailer specializing in exports....

  • Adapter pattern
    Adapter pattern
    In computer programming, the adapter pattern is a design pattern that translates one interface for a class into a compatible interface...

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK