Why do we love classes and object-orientated programming (OOP)? Because we are lazy and don’t want to retype the same lines of code over and over again. With OOP the code is quicker to write and it is easier to be read and maintained.
Before we begin, let us make sure, that we all have a common understanding of the terms used.
Class – a template from which objects are instantiated, in our example
Animal. A class is a general like a blueprint for a house, whereas an instantiated object is a house built using the blueprint.
Instance – an object which has been created from a class, in our example
Attribute – assigned characteristic to the objects. In our example, e.g. ‘color’.
Method – a function which can be performed by an instance of an object, and which might use the object’s to access the attribute.
Classes are mostly used for code that can be logically linked and grouped together. In our example we will create the class
Animal with the instances
giraffe. For these instances we will set the attributes
color. Afterwards, let us print the animal names. Please keep in mind that class names are capitalized and method names are written in lower cases with words separated by an underscore. This way we code compliant to the PEP-8 style guiding rules for Python.
The code then looks like this using the keyword with
pass, as the class is empty. This allows to define the class without filling it with any methods or attributes.
class Animal(object): pass dog = Animal() cat = Animal() giraffe = Animal() dog.name = 'Dot' dog.legs = 4 dog.color = 'brown' cat.name = 'Fluffy' cat.legs = 4 cat.color = 'red' giraffe.name = 'Daisy' giraffe.legs = 4 giraffe.color = 'yellow' print(dog.name) print(cat.name) print(giraffe.name)
The result would be:
Dot Fluffy Daisy
So long!!! And I had to copy paste and rewrite words. As written before, we are lazy and don’t like inefficient, lengthy code that no one wants to read. So now you want to know how we can make this code efficient and add some extra functionalities? Then let’s start with OOP.
Object oriented programming (OOP)
Let us check out step by step how we could shorten and optimize this code. Every animal we create is an instance of this class. Set the instance attributes
color. This can be done within the
__init__ method. The basic first lines of code when defining a class is always the
__init__ method which initializes the object with self being the instance.
self is a parameter which references the object. It is always the first argument in a method and makes it possible to access attributes and methods of the object whose method is called, even though the method comes from the class and thus is written before an object of that class has been instantiated and named. Also the attribute variables of interest are set.
class Animal(object): def __init__(self, name, legs, color): self.name = name self.legs = legs self.color = color giraffe = Animal('Daisy', 4, 'yellow') print(giraffe.name)
This code will print the name ‘Daisy’. For all the three animals being instantiated, the total code with the same functionality as our initial one would be:
class Animal(object): def __init__(self, name, legs, color): self.name = name self.legs = legs self.color = color dog = Animal('Dot', 4, 'brown') cat = Animal('Fluffy', 4, 'red') giraffe = Animal('Daisy', 4, 'yellow') print(dog.name) print(cat.name) print(giraffe.name)
Yielding the same result as above:
Dot Fluffy Daisy
This should already convince you that OOP makes the code a lot cleaner and clearer. The next person using your code will definitely thank you. But the fun and functionalities does not stop there. Let us now define a new method. For example, we will define a method, where some of the animal info is printed out. For simplicity, we will only use the giraffe.
class Animal(object): def __init__(self, name, legs, color): self.name = name self.legs = legs self.color = color def get_info(self): print('The animal is called ' + self.name + ' and is ' + self.color + '.') giraffe = Animal('Daisy', 4, 'yellow') giraffe.get_info() print(Animal.get_info())
Will yield the output
The animal is called Daisy and is yellow. The animal is called Daisy and is yellow.
Interestingly, the code lines
lead to the same output. Can you explain why?
Now, as a further step let the animals interact with each other. This highlights another possible application and functionality of classes. We thus write a new method in which the animals play with each other. The names of the playing animals are then printed. In our example, the giraffe (
self) is playing with the dog (
class Animal(object): def __init__(self, name, legs, color): self.name = name self.legs = legs self.color = color def play(self, friend): print(self.name + ' is playing with '+ friend.name +'.') dog = Animal('Dot', 4, 'brown') cat = Animal('Fluffy', 4, 'red') giraffe = Animal('Daisy', 4, 'yellow') giraffe.play(dog)
The output will then be:
Daisy is playing with Dot.
So NOW you are convinced aren’t you? We hope that these examples helped you to understand the basic theory behind the new material. Please have fun coding and enjoy learning by doing. In case you have any questions the FSE team will be there to support you :).