问题
I thought that I realized this relationship: In Python everything is an object, and every object has a type. But what about classes? A class is a blueprint of an object, and an object is instance of a class. But I have read in an article that in Python, classes are themselves objects. I thought that an object cannot exist without its blueprint - its class. But, if class is an object, how it can exist?
>>> type.__bases__
(<class 'object'>,)
>>> int.__bases__
(<class 'object'>,)
>>> str.__bases__
(<class 'object'>,)
So, the class object
is the blueprint of every object?
>>> type(str)
<class 'type'>
>>> type(int)
<class 'type'>
>>> type(type)
<class 'type'>
So, class type
is blueprint of every other type?
But type
is an object itself. I cannot understand this. I cannot imagine that classes are objects.
回答1:
Everything that can be given a name in Python is an object - including functions, classes and metaclasses. Every object has an associated type or class (these are two names for the same thing -- "type" and "class" are the same in Python 3). The type itself is an object again, and has itself an associated type. The type of a type is called a metaclass (of course, it could equally well be called a metatype, but the latter word is not used). You can use type()
to determine the type of an object. If you iteratively query the type of an object, the type of its type and so on, you will always end up with the type type
at some point, usually after two steps:
type(3) # --> int
type(int) # --> type
type(type) # --> type
Another example, using "meta-metaclasses":
class A(type):
pass
class B(type, metaclass=A):
pass
class C(metaclass=B):
pass
c = C()
type(c) # --> C
type(C) # --> B
type(B) # --> A
type(A) # --> type
type(type) # --> type
There is no contradiction in type
being itself of type type
.
来源:https://stackoverflow.com/questions/5050654/relationship-between-objects-and-classes-in-python-3