Data Science Posts and Resources

Articles on Data Science

Python - Classes and Objects

Introduction to Python Classes and Objects

Laxmi K Soni

6-Minute Read


Classes and Objects

Python is an object-oriented language which means that the code can be divided into individual units, namely objects . Each of these objects is an instance of a so-called class . You can think of the class as some sort of blueprint. For example, the blueprint of a car could be the class and an object would be the actual physical car. So a class has specific attributes and functions but the values vary from object to object.

Creating Classes

In Python, we use the keyword class in order to define a new class. Whatever which is indented after the colon belongs to the class.

class Car:
  def __init__ ( self , manufacturer, model, hp):
         self .manufacturer = manufacturer
         self .model = model
         self .hp = hp

After the class keyword, we put the class name. In this example, this is Car .

Constructor

What we find first in this case, is a special function called init . This is the so-called constructor. Every time we create an instance or an object of our class, we use this constructor. As you can see, it accepts a couple of parameters. The first one is the parameter self and it is mandatory. Every function of the class needs to have at least this parameter. The other parameters are just our custom attributes. In this case, we have chosen the manufacturer, the model and the horse power (hp). When we write self.attribute , we refer to the actual attribute of the respective object. We then assign the value of the parameters to it.

Adding Functions

We can simply create and add functions to our class that perform certain actions. These functions can also access the attributes of the class.

class Car:
  def __init__ ( self , manufacturer, model, hp):
    self .manufacturer = manufacturer
    self .model = model
    self .hp = hp
    
    def print_info( self ):
      print ( 'Manufacturer: {}, Model: {}, HP; {}'.format( self .manufacturer, self.model,self.hp))

Here we have the function print_info that prints out information about the attributes of the respective object. Notice that we also need the parameter self here.

Class Variables

In the following code, you can see that we can use one and the same variable across all the objects of the class, when it is defined without referring to self .

class Car:
  amount_cars = 0
  def __init__ ( self , manufacturer, model, hp):
    self .manufacturer = manufacturer
    self .model = model
    self .hp = hp
    Car.amount_cars += 1
    
  def print_car_amount( self ):
    print ( 'Amount: {}'.format(Car.amount_cars)) 
  
  def print_info( self ):
    print ( 'Manufacturer: {}, Model: {}, HP; {}'.format( self .manufacturer, self.model,self.hp))  

The variable amount_cars doesn’t belong to the individual object since it’s not addressed with self . It is a class variable and its value is the same for all objects or instances. Whenever we create a new car object, it increases by one. Then, every object can access and print the amount of existing cars.

Destructors

In Python, we can also specify a method that gets called when our object gets destroyed or deleted and is no longer needed. This function is called destructor and it is the opposite of the constructor .

class Car:
  amount_cars = 0
  
  def __init__ ( self , manufacturer, model, hp):
    self.manufacturer = manufacturer
    self.model = model
    self.hp = hp
    Car.amount_cars += 1
    
  def __del__ ( self ):
    print ( 'Object gets deleted!' )
    Car.amount_cars -= 1 
    
  def print_car_amount( self ):
    print ( 'Amount: {}'.format(Car.amount_cars)) 
  
  def print_info( self ):
    print ( 'Manufacturer: {}, Model: {}, HP; {}'.format( self .manufacturer, self.model,self.hp))     

The destructor function is called del . In this example, we print an informational message and decrease the amount of existing cars by one, when an object gets deleted.

Creating Objects

Now that we have implemented our class, we can start to create some objects of it.

myCar1 = Car( 'Tesla1' , 'Model X1' , 5251 )

First, we specify the name of our object, like we do with ordinary variables. In this case, the object is called myCar1 . We then create an object of the Car class by writing the class name as a function. This calls the constructor, so we can pass our parameters. We can then use the functions of our car object.

myCar1.print_info()
## Manufacturer: Tesla1, Model: Model X1, HP; 5251
myCar1.print_car_amount()
## Amount: 1

The results look like this: Manufacturer: Tesla, Model: Model X, HP; 525 Amount: 1 What you can also do is directly access the attributes of an object.

print (myCar1.manufacturer)
## Tesla1
print (myCar1.model)
## Model X1
print (myCar1.hp)
## 5251

Now we can create some more cars and see how the amount changes.

myCar1 = Car( 'Tesla1' , 'Model X1' , 525 )
## Object gets deleted!
myCar2 = Car( 'BMW1' , 'X31' , 2001 )
myCar3 = Car( 'VW1' , 'Golf1' , 1001)
myCar4 = Car( 'Porsche1' , '9111' , 5201 )
del myCar3
## Object gets deleted!
myCar1.print_car_amount()
## Amount: 3

Here we first create four different car objects. We then delete one of them and finally we print out the car amount. The result is the following: Object gets deleted! Amount: 3 Notice that all the objects get deleted automatically when our program ends. But we can manually delete them before that happens by using the del keyword.

Hidden Attributes

If we want to create hidden attributes that can only be accessed within the class, we can do this with underlines .

class MyClass:

  def __init__ ( self ):
    self.__hidden = 'Hello'
    print ( self .__hidden) # Works
    
m1 = MyClass()
# print (m1.__hidden) # Doesn't Work 
## Hello

By putting two underlines before the attribute name, we make it invisible from outside the class. The first print function works because it is inside of the class. But when we try to access this attribute from the object, we can’t.

Inheritence

One very important and powerful concept of object-oriented programming is inheritance . It allows us to use existing classes and to extend them with new attributes and functions. For example, we could have the parent class which represents a Person and then we could have many child classes like Dancer, Policeman, Artist etc. All of these would be considered a person and they would have the same basic attributes. But they are special kinds of persons with more attributes and functions.

class Person:
  def __init__ ( self , name, age):
    self .name = name
    self .age = age
    
  def get_older( self , years):
    self .age += years
    
class Programmer(Person):
  def __init__ ( self , name, age, language):
    super (Programmer, self ). __init__ (name, age)
    self .language = language
    
def print_language( self ):
  print ( 'Favorite Programming Language: {}'.format( self .language)) 

Say Something

Comments

Nothing yet.

Recent Posts

Categories

About

about