Is the subclass from the object the same as defining a metaclass type?

This is an old style class:

class OldStyle: pass 

This is a new style class:

 class NewStyle(object): pass 

This is also a new style class:

 class NewStyle2: __metaclass__ = type 

Is there any difference between NewStyle and NewStyle2 ?

I got the impression that the only inheritance effect from object is to actually define the type meta tag, but I can’t find any confirmation of this, except that I don’t see any difference.

+5
source share
1 answer

Pretty much yes, there is no difference between NewStyle and NewStyle2 . Both are of type type , and OldStyle type classobj .

If you are a subclass of an object, __class__ of object ( type value) will be used ; if you provide __metaclass__ to be raised .

If nothing is specified as __metaclass__ and you do not inherit from object , Py_ClassType assigned as a metaclass for you.

In all cases, a call to metaclass.__new__ will be called. For Py_ClassType.__new__ is a certain semantics (I never studied it), and for type.__new__ it should pack object in the fundamentals of your class.

Of course, a similar effect is achieved by:

 cls = type("NewStyle3", (), {}) 

where the type call is immediately executed; this is just a big problem :-)

+2
source

All Articles