Python Introduction | Using Classes | Functions and Classes

A function groups a process into one unit. As the number of functions increases, however, it becomes difficult to understand the role of each function. Understanding hundreds of unrelated functions would be challenging.

A natural solution is to group things with similar roles.

For example, consider data processing. A long list of separate functions for managing, adding, deleting, and displaying data is not easy to use.

Instead, group everything needed to process the data. Create a large data-related unit containing variables for storing data and functions for reading, writing, adding, deleting, and displaying data.

Then you know that anything related to the data is available inside that group. You do not need to search for functions scattered throughout the code.

This is the idea behind a class. A class groups the values and processes required for a purpose.

Define a class as shown below. Start with class ClassName: and indent the variables and functions provided by the class.

Defining a Class

class ClassName:
  variable1
  variable2
  ...... provide as many variables as needed ......

  def method1(arguments):
      ...... method process ......
   
  def method2(arguments):
      ...... method process ......
   
  ...... provide as many methods as needed ......

Variables that store values required by a class are called member variables. Functions provided by a class are called methods.

The syntax is fundamentally the same as the syntax for ordinary variables and functions. Writing them inside a class definition makes them member variables and methods.