Search

Object Oriented Programming (OOP) In Python: Classes and Objects Part 1

Computer scientists are continually refining how they write programs. Therefore, they have resorted to several methodologies to do so. Object Oriented Programming (OOP) is a popular methodology and it is the methodology that python relies on. Other programming languages that rely on the OOP methodology include Java and C++.

oop in python class and object

 

Object oriented programming as the name implies relies on objects as its main concept, and along with other related features of objects like classes, inheritance, abstraction and encapsulation. This is a wide departure from functional programming which depend on functions as its main concept. In OOP, every operation is defined as an object and every attribute is based on that owned by the object.

Object oriented programming has become popular because it brings programming close to real life, to the things people could associate with, and not to mathematical functions that are most times the province of professional scientists and mathematicians.

In python, we will start by describing how python implements classes and objects in OOP before we relate it to other features of OOP in python.

Python Class in OOP.

A class is a blueprint for defining data and behavior of objects. It helps us to define similar objects and relate them to a class. For example if you have two dogs, one called “James” and another called “Bingo”, these dogs are both objects with similar behavior and properties. Therefore, we could create a Dog class for both objects.

When we create a python class, we are bringing together the data and behavior of an object and defining them in a bundle. Therefore, creating a new python class is the same thing as creating a new type of object in python and with the ability that new instances of that type can then be made. For example, if we create a Dog class from the example above, new instances of dogs named ‘James’ and ‘Bingo’ can then be made. These class instances are given the attributes defined in the class to maintain their state, and they can also have methods defined by the class for modifying their state.

It is through the python class definition that we can then implement all the features of object oriented programming in python such as class inheritance allowing for multiple child classes, the overriding of the methods of a parent class by a child class, and a child class having methods that have the same name as the parent class. Note that the amount and kinds of data that objects can contain that are derived from a class is unlimited. Just like modules, classes in python are dynamic in nature since they are created at runtime and can be modified after creation.

The following is the syntax of a python class definition:

    
class ClassName:

    statement 1
    statement 2
    

To define a python class you need to use the keyword class to precede the name of the class. Then the name of the class is followed by a colon. The colon delimits the block of statements that represents what goes into a class like the attributes and methods that the class defines for its objects.

Before a python class definition can have any effect, it must be executed like function definitions. The moment you call a python class, you are creating an object, called class instantiation. You can create and call a class this way:

    
# class definition
class Dog:
    
    def method1():
        statement 1...

# class execution. Creates an object
james = Dog()
        
        

When a class is called, a new namespace is formed which includes all the attributes and methods of the class.

Most times when you are instantiating an object or creating an object, you define the instantiation special method, __init__(). This special method contains all the attributes of the object instances that are needed when objects are created. Therefore, when this exists, the moment you invoke the class by creating an object, the object creation process automatically calls the __init__() special method and implements any statement that are contained within the special method.

For example, let’s take a class Animal that specifies that whenever an Animal object is created, it has to be given a name that would be bound to the object. We could write the code with the __init__() special method this way.

    
# class definition
class Animal:
    
    def __init__(self, name):
        ''' name is a string '''
        self.name = name

# class execution. Creates an object
james = Animal('James')

With the code above any Animal object that is created will be supplied a name. Here we gave the animal the name, James. That name is bound to the python object, james, throughout its lifetime and is unique to it.

Python classes also contain data attributes and methods. The data attributes are of two types: data attributes that are generalized for the class and is applicable to all objects (called class variables) and data attributes that are specific to each instance of a class or each object and called instance variables. I will show how class variables are distinguished from instance variables in another section. But note that the ‘name’ attribute for our Animal class above is an instance variable because it pertains to each specific object of the class.

Python class methods are operations that will be performed by the objects of the class. A method is a function that “belongs to” an object. We add the self parameter when defining methods in a class. This tells the python interpreter that the method belongs to the class that called it. But this need not be enforced although many editors will tell you there was an error if you do not insert the self parameter. Let us illustrate an example of an animal that walks and talks below.

Notice that every method of the class has self as the first parameter. The methods walk and talk define what each object of the animal can do.

Python Objects and OOP.

Objects are the physical entities of the world. They serve as a realization of classes which are the logical entitites. An object can be anything – a book, a student, an animal etc. Objects are defined by three important characteristics: (A). An identity or a piece of information that can be used to identify the object e.g name, number. (B). Properties. The attributes of the object. (C). Behavior. These refers to the operations that are done on the object or the functions it can perform. E.g a student can write, a car can move, an animal can walk.

Objects of a python class support two types of operations: attribute reference and instantiation. I have outlined these two operations in the embedded code above but will bring them out again for emphasis.

In python, the standard syntax for attribute references is the dot syntax. In the above code, when referring to the method walk and talk, we used objectname.walk() and objectname.talk(). Also, in the walk and talk methods when referring to the name data attribute we used self.name. Valid attribute names are all the names that are in the class’s namespace when the python object was created following from the class definition.

Class instantiation that creates a python object uses function notation. Class instantiation results in the creation of an object for the class. We denoted class instantiation above with the code: james = Animal(‘James’) where Animal refers to the class Animal. Animal here is being used as a function to create the object james. The class instantiation function can have an argument or no argument based on how you defined your __init__() method. In our __init__() function above we specified that on object creation we need to supply a name for the object.

Python Class and instance variables in OOP.

As we said above, class variables refer to data and methods that are shared by all instances of the class, while instance variables refer to data and methods that are specific and unique to each instance of a class. If you want an attribute to be a class variable, you should not initialize it in the __init__() method but if you want it to be an instance variable you should initialize it in the __init__() special method. Let’s denote these with examples below.

From the example above you can see that we created two Animal objects, james and frog. In the class definition we defined the type attribute outside the __init__() method and therefore when we call it for both objects we have the same value or reply. But we defined the name attribute inside the __init__() method and then when we called the name attribute we received different values for both objects. Always remember this difference between class variables and instance variables in your code so you don’t get code that doesn’t work as you expect when creating classes and objects.

Data Hiding in Python.

In other object oriented programming languages like java they give you the ability to hide data from users getting access to them from outside the class. In this way, they make data private to the class. The makers of python do not want any data hiding in the language implementation. They state that they want everything in python to be transparent. But there are occasions where you can implement data hiding. This can be achieved by prefixing the attribute with a double underscore, __. When this is done you cannot directly access the attribute outside the class.

For example, let’s make the type attribute hidden in the Animal class.

You can see now that to reference the type attribute we get an AttributeError. But there is a workaround that we can use to get the attribute. When you call objectname._Classname__attributename you can get back that attribute. So nothing is hidden in python. Let’s show this with an example. Take note of line 16 in the code below.

It is beneficial to understand how python implements OOP extensively because when you are working in python, you not only use the built in types but have to create your own types. I hope this post helped you along that line. The subsequent posts will treat on other OOP concepts like python class inheritance in OOP and OOP in python - polymorphism that will build on this knowledge. I hope you also enjoy them.

Happy pythoning.

3 comments:

Your comments here!

Matched content