I was reading about this excellent post on metaclasses What is a metaclass in Python? . The accepted answer shows how to create a class using type
with the following signature.
type(name of the class,
tuple of the parent class (for inheritance, can be empty),
dictionary containing attributes names and values)
That makes me wonder who creates the object class. Is object class also created by type
class?
In theory you are correct. object
is an instance of type
. But, when you check type
's base classes, you'll find that type
inherits from object
! How can this be?
The truth is, this is hard-coded in the Python interpreter. Both object
and type
are given; neither is actually involved in any way with creating the other.
The main thing to remember at these rarified levels of the object/type hierarchy is that things like object
and type
are not created in .py files at all, they are created statically in C code, along with the rest of the foundational underpinnings of CPython. So they aren't necessarily "created" with any particular Python code.
type
is a bit of a - umm, not sure how to describe it - weirdo of the language.
It can be used to do type(someobj) or used as a constructor (with 3 params) of some sorts to create new types derived from a base with instances. As you have seen with meta-classes - it's useful to make factory classes - although, IMHO unless you really want to be too clever, using class decorators makes this slightly easier in 2.6+
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.