1

When are objects of type type instantiated in Python?

I understand that Python classes are objects themselves (being instances of class type). When are these objects instantiated?

I guess it's either on module import or on the first instantiation of the class, but I could not find any documentation on this topic. I'm especially interested in answers for Python 2.7, but would like to be pointed to (possible) differences in Python 3 as well.

nbro
  • 15,395
  • 32
  • 113
  • 196
karlson
  • 5,325
  • 3
  • 30
  • 62
  • 1
    Classes are created whenever Python executes them (i.e. where you wrote `class`), like any other object. – Colonel Thirty Two Feb 28 '15 at 22:48
  • 2
    All new-style classes are of type `type`, and they are created when a `class` statement is executed or you explicitly use the `type()` callable to create a class. Is that what you are looking for? Your question is somewhat unclear. – Martijn Pieters Feb 28 '15 at 22:48
  • 1
    Related: [Why does a class' body get executed at definition time?](http://stackoverflow.com/q/26193653) – Martijn Pieters Mar 01 '15 at 00:04

1 Answers1

5

They are instantiated as soon as the end of the class scope is reached.

class foo(object):
  pass

bar = foo # Works

print type(foo)

class foo2(object):
  bar = foo2 # NameError
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358