Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Metaclass
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Python example== In [[Python (programming language)|Python]], the builtin class <code>type</code> is a metaclass.<ref>IBM Metaclass programming in Python, parts [http://www.ibm.com/developerworks/linux/library/l-pymeta.html 1] {{webarchive|url=https://web.archive.org/web/20080903123731/http://www.ibm.com/developerworks/linux/library/l-pymeta.html |date=2008-09-03 }}, [http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/ 2] and [http://www.ibm.com/developerworks/library/l-pymeta3.html 3]</ref><ref>Artima Forum: Metaclasses in Python 3.0 [http://www.artima.com/forums/flat.jsp?forum=106&thread=236234 (part 1 of 2)] [http://www.artima.com/forums/flat.jsp?forum=106&thread=236260 (part 2 of 2)]</ref><ref>{{cite web | url=http://www.onlamp.com/lpt/a/3388 | title=A Primer on Python Metaclass Programming | author=David Mertz | work=[[O'Reilly Media|ONLamp]] | accessdate=June 28, 2006 | url-status=dead | archiveurl=https://web.archive.org/web/20030430162409/http://www.onlamp.com/lpt/a/3388 | archivedate=April 30, 2003 }}</ref> Consider this simple Python class: <syntaxhighlight lang="python"> 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}" </syntaxhighlight> At run time, <code>Car</code> itself is an instance of <code>type</code>. The source code of the <code>Car</code> class, shown above, does not include such details as the size in bytes of <code>Car</code> objects, their binary layout in memory, how they are allocated, that the <code>__init__</code> method is automatically called each time a <code>Car</code> is created, and so on. These details come into play not only when a new <code>Car</code> object is created, but also each time any attribute of a <code>Car</code> is accessed. In languages without metaclasses, these details are defined by the language specification and can't be overridden. In Python, the metaclass - <code>type</code> - controls these details of <code>Car</code>'s behavior. They can be overridden by using a different metaclass instead of <code>type</code>. The above example contains some redundant code to do with the four attributes <code>make</code>, <code>model</code>, <code>year</code>, and <code>color</code>. It is possible to eliminate some of this redundancy using a custom metaclass. In Python, a metaclass is most easily defined as a subclass of <code>type</code>. <syntaxhighlight lang="python"> 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 </syntaxhighlight> This metaclass only overrides object creation. All other aspects of class and object behavior are still handled by <code>type</code>. Now the class <code>Car</code> can be rewritten to use this metaclass. In Python 3 this is done by providing a "keyword argument" <code>metaclass</code> to the class definition: <syntaxhighlight lang="python"> 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()) </syntaxhighlight> The resulting object <code>Car</code> can be instantiated as usual, but can contain any number of keyword arguments: <syntaxhighlight lang="python"> new_car = Car(make='Toyota', model='Prius', year=2005, color='Green', engine='Hybrid') </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)