Metaclass
In object-oriented programming, a metaclass is a class whose instances are classes themselves. Unlike ordinary classes, which define the behaviors of objects, metaclasses specify the behaviors of classes and their instances. Not all object-oriented programming languages support the concept of metaclasses. For those that do, the extent of control metaclasses have over class behaviors varies. Metaclasses are often implemented by treating classes as first-class citizens, making a metaclass an object that creates and manages these classes. Each programming language adheres to its own metaobject protocol, which are the rules that determine interactions among objects, classes, and metaclasses.[1] Metaclasses are utilized to automate code generation and to enhance framework development.[2] Python exampleIn Python, the builtin 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"{self.color} {self.make} {self.model}"
At run time, The above example contains some redundant code to do with the four attributes 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 Now the class 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 new_car = Car(make='Toyota', model='Prius', year=2005, color='Green', engine='Hybrid')
In Smalltalk-80In Smalltalk, everything is an object. 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 Class methods actually belong to the metaclass, just as instance methods actually belong to the class. When a message is sent to the object When a message is sent to In early Smalltalks, there was only one metaclass called Since there is no requirement that metaclasses behave differently from each other, all metaclasses are instances of only one class called In Smalltalk-80, every class (except The superclass hierarchy for metaclasses parallels that for classes, except for class
Like conjoined twins, classes and metaclasses are born together. The names of classes in the metaclass hierarchy are easily confused with the concepts of the same name. For instance:
Four classes provide the facilities to describe new classes. Their inheritance hierarchy (from Object), and the main facilities they provide are:
In RubyRuby purifies the Smalltalk-80 concept of metaclasses by introducing eigenclasses,
removing the
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.[7] The following diagrams show a sample core structure of Smalltalk-80 and Ruby in comparison.[8]
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
The diagram on the right also provides a picture of lazy evaluation of eigenclasses in Ruby. The According to the Ruby's introspection method named In Objective-C
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 There are no names for the metaclasses; however, a pointer to any class object can be referred to with the generic type 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 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.[10] Support in languages and toolsThe following are some of the most prominent programming languages that support metaclasses.
Some less widespread languages that support metaclasses include OpenJava, OpenC++, OpenAda, CorbaScript, ObjVLisp, Object-Z, MODEL-K, XOTcl, and MELDC. Several of these languages date from the early 1990s and are of academic interest.[12] Logtalk, an object-oriented extension of Prolog, also supports metaclasses. Resource Description Framework (RDF) and Unified Modeling Language (UML) both support metaclasses. See alsoReferences
External links |
Portal di Ensiklopedia Dunia