Introduction to Classes and Objects

Perhaps you have heard about Object Oriented Programming (OOP). Object Oriented Programming is a programming paradigm that allows for the construction of autonomous entities within our programs which are denominated 'Objects'.

Objects are bundles of data and methods that can be recognized to have some clear autonomous behavior. You can create objects for very tangible elements within your program, such as a 'bouncing ball' or more abstract elements such as a 'Manager' or 'File Exporter'.

Within OOP we are able to create and name our own objects based on what makes sense for the project. This gives us great flexibility but also might become a daunting task when learning how to code, as there are many possible paths of how to describe some logic as objects.

But we will start defining the vocabulary;

In order to create an Object, we will need to create a 'Class'. This is the first challenging concept, what are classes and how are they different from objects?

Think of a class as a template of an object or an outline of an object . The class provides instructions on how an object is constructed.

The class comes first. and is a declaration of the data and methods that will be contained in the object.

Once we have a class, we can use the class to construct an object.

The object then, is an instance of a class; the code defined by the class 'in action'.

While the class declares the kind of data an object would have, the object contains the actual data.

Let's look at an example of how to construct a simple class, and how to construct an object from it;

#class declaration
class MyClass(object):
    
    #constructor
    def __init__(self, name): # constructor
        self.name = name   # assign local variable in object
    
    #functions of the class
    def print_my_name(self):
       print("My name is: " + self.name)

#create a class instance
M = MyClass("Lucy")
print (M)
#execute some of the functions
M.print_my_name()

As you can see, a class introduces a lot of new syntax.

Notice that lines 1-10 are the declaration of the class, and from line 13 we start using the class to create an instance of the class, the object.

Besides the 'class' declaration in line 2, you will see that in line 5, we have a new concept. This is a 'constructor'.

The constructor of a class is a special method that allows us to initiate the class with some specific variables. In the example above, we can see that the class 'Dog' can receive a name and an age when created. This is defined in the constructor function.

Variables that exist within the class can be accessed with the keyword ' self ', to denominate variables that are internal to the class.