Understanding the use of Classes

I would like in this blog to shed some light over the utility of a class. Though I will be using Python, these concepts  apply regardless the programming language used.

Definition: A class is nothing more than a special data structure template which encapsulates data and functionality in one place. In practical terms, a class defines a data type.

In fact, it is most likely that you have already used a class. For example, when we create an int variable, we are actually creating an object (the variable) of data type int which in turn, is defined in the int class. 

Conceptually, the class Int could look something like this:

Class int

  • Attributes:
    • Value – this is the actual numeric value
  • Functions or Methods:
    • Create :: this is called the constructor and it’s a special function which creates the actual object
    • Add :: implements addition
    • Subtract :: implements subtraction
    • Multiply :: implements multiplication
    • Devide :: implements division

In this section I will create a class called clsPerson which will represent a person (duh!):

clsPerson

Attributes: 

  • fname – this is a string which holds the person’s first name
  • lname – this is a string which holds the person’s last name
  • bday – holds the person’s birthdate

Functions:

  • __init__ – this is the constructor
  • GetAge() – this function returns the age of the person

The Python code to create this class is the following – refer to the comments inline:

I suspect that after looking at the code, you would still be a bit confused regarding the self keyword … Check the comments below:

The loop generates the following output:

Cabral, Rafael is 41 of age.
Smith, John is 36 of age.


In the future, if we need to extend functionality, we just need to add additional attributes and functions to the class without changing existing code.

CONCLUSION/RECAP

  1. Classes create data types
  2. A class is a data structure which encapsulates attributes and functions
  3. Allows us to reference the objects as a logical unit
  4. Provide scalability

 

Thank you,

Rafael A. Couto Cabral • LinkedIn Profile
Cisco​ | F5 | VMware Certified • PRINCE2 Practitioner

Originally posted 2017-11-23 01:51:09.

Related Post

Comments are closed.