What It Means That Classes Themselves Are Callable In Python

1. THREE, NOT TWO ABSTRACTION LEVELS

  • NOTE: this section is my speculation / double-check!
>>> type(list)  # list is a python-class
<class 'type'> # this literal 'class' refers the most abstract class; NOT an object
>>> l = list()
>>> type(l)
<class 'list'>

2. EVERYTHING IN AN OBJECT

  • Remember that Everything is an Object in Python and that includes classes — which may be confusing.
  • In other words, the object-orientation as interacted with (the 2nd and 3rd layer mentioned above) is built on top of the everything is an object principle
  • Therefore, a defined class that has not yet been instantiated, is also/already an object (factory) of class type
  • This is the same principle with function declaration: the def keyword binds a function to a named reference (important Python concept) → and already creates a function object (object of class function) without function ever being invoked.
  • The class keyword not only declares a class, it binds a class object to a named reference
  • However/of course: class-objects and class-instances are very different things (layer 2 VS layer 3 above)
  • Calling the class object itself in REPL returns
>>> Resolver()
<Resolver object at 0x04120D90>
  • … and the arguments passed will be forwarded to the class’s __init__()

3. USE IN FUNCTIONS

  • example: a function producing a Python sequence type based on a primitive logic: a tuple if immutable is requested or a list if mutable is requested
  • NOTE: that you cannot use class for variable name; the popular alternatives one may encounter are
  1. klass — misspelled, a bit more explicit

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com