Reputation: 157
I've little bit test to fully understand metaclass in python.
class Test(object):
pass
print Test.__class__
print Test.__class__.__class__
print Test.__class__.__class__.__class__
All of result is same type
. but each of their address is not same
I can't really understand why metaclass has a metaclass recursively.
Explain me please?
Upvotes: 1
Views: 143
Reputation: 1856
All the python's class object is build by the built-in function type(). You could also try this.
>>> T.__class__ == type
True
>>> type(type)
<type 'type'>
The T.class is equal to the build-in function type which is also an object implemented the call function. It's a attribute will be interpret as class(T). As your T class have no base class so type() is used which will return the type object.
You could check the python doc about customizing class creation to get detail about class creation.
To determining the appropriate metaclass
Upvotes: 0
Reputation: 29727
Actually, addresses are the same:
>>> id(Test.__class__)
6384576
>>> id(Test.__class__.__class__)
6384576
>>> id(Test.__class__.__class__.__class__)
6384576
Everything is an object in Python, and each object must have a class (it should belong to some type). You can access that class/type reference by __class__
attribute, e.g.:
>>> (1).__class__
<type 'int'>
Everything includes classes itself, which are of class/type called type
:
>>> (1).__class__.__class__
<type 'type'>
In the same time type 'type'>
is also an object and should reference to some class/type. But since this is kind of special object, its __class__
attribute refers to itself:
>>> (1).__class__.__class__.__class__ is (1).__class__.__class__
True
Upvotes: 2
Reputation: 28405
All classes are classes which means they are derived from a class called class...
Upvotes: 0
Reputation: 5846
When you do Test.__class__
, you get back the type of Test
, which is type
(because Test
is a class identifier).
type
itself is again a class identifier, so you can call __class__
(which is inherited from object
) on it and you get back that its type is, again, type
because it is a class identifier.
Because you will always get back type
which is a class itself, you can do this infinitely many times and will always get back that the current object's type is type
.
Upvotes: 0