Classes And Objects

Class Definition

Class is a blueprint in which characteristics (properties) and behaviors (functions) are defined.

An example of class definition is:

In the example:

  • class is the keyword for class defining.
  • Person - the name of the class.
  • pass is used only if the class body is empty (it avoids exception throw).

Object Creation

Object is an instance created from a class.

Using the defined class we can create objects and set properties.

Output:

Explanation:

  • At lines 1 - 3 a class is defined.
  • The class has a function introduceYourself that uses the properties of a class object via the self parameter.
  • Notice that class function must always have at least 1 parameter. That's because the first argument (self) points to the class object.
  • At line 6 an object is created.
  • At lines 9 and 10 values are set to the properties.
  • At lines 12 the function introduceYourself is called and a message is printed.