An operational explanation of Python metaclasses (part 3)September 18, 2011
Following on from part 1 and part 2, the third thing that we can do with a metaclass is to create 'class-only attributes', attributes that are only visible on the class and not on instances of the class. In fact we can go further than just adding attributes; we can control what attributes are directly visible on the class without affecting what attributes are visible on instances of the class. Simply adding attributes to the class (and only to the class) is done by putting attributes on the metaclass; in fact all attributes on the metaclass are visible on the class but not on instances of the class. Since this has some subtle bits, here is an example to illustrate: class MiniMeta(type): one = "meta" two = "meta" class Alpha(object): two = "alpha" class Beta(Alpha): __metaclass__ = MiniMeta bi = Beta()
The exception to parent classes taking priority is properties. A property set on the metaclass overrides anything else when you access it on the class, but is invisible to instances of the class. If you try hard this can be used to create attributes that have one value on the class and another value on instances of the class, which is sure to confuse everyone who reads your code unless you comment it heavily (and maybe even then). The advanced version of this is that you can get partial or (almost)
full control of attribute access to the class itself by setting
up (As with properties, this can be abused to create attributes which have a different value on the class than on instances of the class.) Note that this not-looking happens even when the lookup on the class
is implicit, such as when you do (As with part 2, this is a specific example of a general metaclass power.) Sidebar: method functions on the metaclass versus
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |