It's All Instantiation, Really
Some questions are probably popping up in your head at this point. Or
maybe they aren't, but I'll answer them anyway:
| Q: | How does Python really create a
new object? |
| A: | Internally, when Python creates a new object, it always
uses a type and creates an instance of that object. Specifically it
uses the __new__()
and __init__() methods of the type (discussion of
those is outside the scope of this book). In a sense, the type serves
as a factory that can churn out new objects (to each of which it is
related as type-instance). This is why every object has a type.
|
| Q: | When using instantiation, I specify the type,
but how does Python know which type to use when I use
subtyping? |
| A: | It looks at the base object that you specified, and uses
its type as the type for the new object. In the example Example 2.4, “Creating new objects by subtyping” , <type 'type'> (the type of
<type 'object'>, the specified base) is used as the type object for
creating C. A little thought reveals that under most circumstances, any
subtypes of <type 'object'> (and their subtypes, and so on) will have
<type 'type'> as their type.
|
Advanced Material Ahead
Advanced discussion ahead, tread with caution, or jump straight to the
next section.
| Q: | Can I instead specify a type object to
use? |
| A: | Yes. One option is by using the
__metaclass__ class attribute as in the following
example:
Example 2.6. Specifying a type object while using class statement
class MyCWithSpecialType(object):
__metaclass__ = SpecialType
Now Python will create MyCWithSpecialType by
instantiating SpecialType, and not
<type 'type'>. |
| Q: | Wow! Can I use any type object as the
__metaclass__? |
| A: | No. It must be a subtype of the type of the base
object. In the above example: Base of MyCWithSpecialType is <type 'object'>. Type of <type 'object'> is <type 'type'>. Therefore SpecialType must be a subtype of <type 'type'>.
Implementation of something like SpecialType
requires special care and is out of scope for this
book. |
| Q: | What if I have multiple bases, and don't specify a
__metaclass__ - which type object will be
used? |
| A: | Depends if Python can figure out which one to use. If
all the bases have the same type, for example, then that will be
used. If they have different types that are not related, then Python
cannot figure out which type object to use. In this case specifying a
__metaclass__ is required, and this
__metaclass__ must be a subtype of the type of
each base. |
| Q: | When should I use a
__metaclass__? |
| A: | Never (as long as you're asking this question anyway
:) |