Introduction to Metaclasses
Python's metaclasses grant the Python OOP ecosystem all the power of more complex object inheritance systems in other languages, while retaining for most uses the simplicity of the straightforward class structures most developers learn when being introduced to object-oriented programming. This talk is an explanation of metaclasses: first, what they are, and second, how to use them.
- Introduction (2.5m)
- Python's metaclasses grant the Python OOP ecosystem all the power of more complex object inheritance systems in other languages, while retaining the simplicity of the straightforward class structure that traditional C++ and Java programmers learned, and is taught in programming courses.
- Classes are Objects, Too! (5m)
- Classes are first-class objects in Python, like functions/methods
- Classes, like other objects, can be assigned to variables and passed as arguments
- ...and this ability is one of the tricks in the reusable code toolbox
- Concept: Metaclasses generate classes. (5m)
- The hierarchy starts with "type"
- Classes are themselves instances of their metaclasses
- By extension, classes provide code that runs when instances are created, while metaclasses provide code that runs when classes are created.
- Remember the "analogies" section on standardized tests in the United States (and many other countries)?
- Babylon 5 : J. Michael Strazynski :: Star Trek : ___
- Instances : Classes :: Classes : Metaclasses
- Think about a self-enclosed machine that creates, say, t-shirts. The machine is the class; the individual shirts are the instances. The guy who builds the t-shirt machines is the metaclass.
- Concrete Code Examples (10m)
- will cover 3.0 and 2.7
- (stub: I haven't decided what my example will be yet)
- Is metaclassing wise? (2.5m)
- There's nothing inherently wrong or bad about it. Furthermore, sometimes it's by far the best way to solve a problem.
- Beware, though: Some people find metaclassing confusing.
- "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." (Brian Kernighan)
- Questions (5m)
About the speaker
Pythonista & Developer, Gamer, Presbyterian
bio from Twitter
Next session in E3
11:30am The Art of Subclassing by Raymond Hettinger
Coverage of this session
to add slides, notes or videos to this session