Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Old-style classes, new-style classes and metaclasses

In Python 2.x, all new-style classes inherit from object implicitly or explicitly. Then look at this:

>>> class M(type):
...     pass
...
>>> class A:
...     __metaclass__ = M
...
>>> class B:
...     pass
...
>>> a = A()
>>> b = B()
>>> type(A)
<class '__main__.M'>
>>> type(a)
<class '__main__.A'>

Does this mean A is a new-style class? But A doesn't inherit from object anyway, right?

>>> type(B)
<class 'classobj'>
>>> type(b)
<type 'instance'>

OK, B is a classic class, isn't it?

>>> isinstance(A, object)
True
>>> isinstance(B, object)
True

why are instances of both A and B instances of object?

If B is an instance of object, then type(B) wouldn't be classobj, right?

like image 408
Alcott Avatar asked May 08 '12 08:05

Alcott


People also ask

What is the difference between old style and new-style classes in Python?

A new-style class is a user-defined type, and is very similar to built-in types. Old-style classes do not inherit from object . Old-style instances are always implemented with a built-in instance type. In Python 3, old-style classes were removed.

What are the metaclasses in Python?

A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.

Are metaclasses inherited?

Defining Metaclasses Principially, metaclasses are defined like any other Python class, but they are classes that inherit from "type". Another difference is, that a metaclass is called automatically, when the class statement using a metaclass ends.

What is __ new __ in Python?

The __new__() is a static method of the object class. It has the following signature: object.__new__(class, *args, **kwargs) Code language: Python (python) The first argument of the __new__ method is the class of the new object that you want to create.


1 Answers

About metaclasses you may read here: http://docs.python.org/reference/datamodel.html#customizing-class-creation. Generally metaclasses are intended to work with new style classes. When you write:

class M(type):
    pass

and you use:

class C:
    __metaclass__ = M

you will create a new style object because the way M is defined (default implementation uses type to create a new-style class). You could always implement you own metaclass that would create old-style classes using types.ClassType.

like image 115
uhz Avatar answered Oct 14 '22 00:10

uhz