5

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?

Alcott
  • 17,905
  • 32
  • 116
  • 173
  • You shouldn't have put the `__slots__` thing in this question. It's another question entirely. – Chris Morgan May 08 '12 at 08:58
  • @ChrisMorgan, yes, I just realized that. – Alcott May 08 '12 at 09:14
  • 2
    A is a new style class, since *'new-style classes are constructed using type()'* and you have set it's metaclass to `type`. Old-style classes use `types.ClassType` – jamylak May 08 '12 at 11:36
  • @jamylak, as you can see, `A` doesn't inherit from `object`, but I still use `__metaclass__` in `A`, is this OK? Cuz I thougt, `__metaclass__` can only be used with class inheriting from `object`, right? – Alcott May 08 '12 at 11:44
  • 1
    `__metaclass__` is used in every class. Every class has a metaclass which constructs it. – jamylak May 08 '12 at 13:28

2 Answers2

5

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.

jamylak
  • 128,818
  • 30
  • 231
  • 230
uhz
  • 2,468
  • 1
  • 20
  • 20
1

About slots you may read here http://docs.python.org/release/2.5.2/ref/slots.html, a fragment:

By default, instances of both old and new-style classes have a dictionary for attribute storage.

For new-style classes you may add __slots__, then the per-object dictionary will not be created.

uhz
  • 2,468
  • 1
  • 20
  • 20