Menu Close

Articles

Python: classes

Python is a multi-paradigm programming programming language but under the hood is Object Oriented. You can define classes and objects similar to other languages like Java and C++. All functions and data types are in fact objects.

Class

A class is a named block of code that contains variables and function declarations. The variables are called “properties” or “attributes”. The functions declared inside a class are called “methods”. 

We can use a class like a code template to create objects during runtime. Each object is dynamically allocated in memory and it has its own namespace. An object can be a named variable or can be an element into a collection.

Objects are also called “instances” of a class. You can create an object using an “object constructor” that is a special method defined in a class, called __init__. It could be called “constructor” but in Python there is a convention to name all private functions with double underscore prefix.

Example:

Output:

Notes:

  1. The __init__  function is the constructor. This has 2 parameters: self and name. When a new object is created from the class Dog, only second parameter is required. First parameter “self” represents the current object.
  2. When you create a new object you use the class name with arguments, but the arguments are received by the __init__ function not by the class. That may be confusing at first since the class has its own parameters representing parent classes.

Caution:

Many developers have difficulty to understand difference between a class attributes and object attributes. Any variable defined in local scope of the class are shared between all objects of the class.  Object attributes, must use self. prefix. Both kind of attributes can be modified in the constructor, but class attributes are shared between objects. That is the difference.

Homework: Open live example and run it: class

Inheritance

A class can inherit from another class called “base class”. 

Example:

Observe: in the constructor of “Dog” we call the super(), this is the super class and __init__() that is the constructor for the base class. The object “Dog” will have all attributes of “Animal” plus some more specific to “Dog” and defined in __init__() constructor.

If the parameter of the class is missing the class will automatically be derived from the most base class, called the “root” class in other languages. This is the “object” class.

Record

Sometimes a developer want’s a structure to hold some data. You can do this with a collection but some neat trick is to use a class with attributes. This kind of class do not require an instance. It can be used as an object:

Note: there is no point to instantiate a class used as record. All instances will have same attributes as the class. These are called class attributes. You can not add new attributes for an object but you can for the class.

Learn next about: Switch