A class is a prototype that is defined by the user in order to create objects out of it. Besides creating objects and data, classes also provide functionality within its body and that makes classes(object-oriented programming) a very useful and efficient concept. As the created object within a class is considered a unique type of object, that allows you to create an infinite number of instances from this object type, also an object type can contain functions not only variables in case your application needs processing or manipulation for the object variables.

  1. Class definition
  2. Object declaration
  3. Self parameter
  4. __init__ function
  5. Functions in classes
  6. Change attribute value
  7. Delete an attribute
  8. Constructors in Python
  9. Destructors in Python

Here’s the advanced guide on Python classes.

Python Classes Tutorial

Class definition

A  class in python is defined using the keyword “class” followed by the class name and a colon. And with proper indentation, statements are presented in the class upon the requirements of the program. Let’s see the syntax:

Code:

class Fruit:
pass
print(Fruit)

Output:

<class ‘__main__.Fruit’>

Object declaration

In other words, it’s called class instantiation, where an object(instance) is created with the same attributes, functionality, and behavior of the class which is created through it. The simplest way to declare an object is by naming it followed by an equal sign and the class name followed by brackets(). Let’s see the syntax:

Code:

class Fruit:
  #class attributes
  x = "Food"
  y = "Fruit"
#object declaration or class instantiation
Banana = Fruit()

print(Banana.x)
print(Banana.y)

Output:

Food
Fruit

Explanation:

As we can see the declared variable has access to the class attributes, and the print statements show us the values of the attributes accessed by the class instance.

Self parameter

The self parameter is a parameter passed manually to functions included in a class, it must be the first argument in the function definition. The self parameter is considered as a reference for the current instance of the class and used to access the attributes of the class. The good thing about the self parameter that its name could be customized as you wish and that makes you differentiate between self parameters for different functions. Let’s see the syntax:

Code:

class Fruit:
  #class attributes
  x = "Food"
  y = "Fruit"
  #class function with self parameter called tree
  def yourfruit(tree):
    print("This class is" , tree.y)
#object declaration or class instantiation
Banana = Fruit()

Banana.yourfruit()
print(Banana.x)
print(Banana.y)

Output:

This class is Fruit
Food
Fruit

Explanation:

As we can see a function named yourfruit() was defined within the class with self parameter name = tree. And the self parameter managed to access the class attribute “y”. And when the function was called later it showed us the output with the class attribute “y”.

__init__ function

As mentioned before, the above methods are for defining specific attributes of values within the class. What if you want to create several objects of the same class but with different values. Python provides __init__ function, similar to constructors in other programming languages like (C++ & Java) the __init__ function is created once an object of the class is instantiated. Its main advantage is initializing values of the attributes when the object is being created, and as it’s a function a self parameter must be passed to it as the beginning. Let’s see the syntax:

Code:

class Fruit:
  def __init__(self,color,weight):
    self.color = color
    self.weight = weight
  #class function with self parameter called tree
  def yourfruit(tree):
    print("This class is" , tree.color)
#object declaration or class instantiation
Banana = Fruit("yellow",0.5)
Banana.yourfruit()
print(Banana.color)
print(Banana.weight)

Output:

This class is yellow
yellow
0.5

Explanation:

While you created an object of the class and passed the attribute’s parameters to the class instance, you managed to assign values to the class attributes using the __init__ function. Now you have the class instance Banana with the customized values for the attributes and that allows you to create multiple objects of the same class with different attributes values.

Functions in classes

As normal functions in python, function within classes is defined the same way using the keyword def followed by the function name and brackets(), where these brackets contain the passed parameters to the function. The only difference between normal functions and class functions is the self parameter that’s passed to functions in classes. Let’s see the syntax:

Code:

class Fruit:
  Food = "fruit"
  #init function to initialize instance attributes
  def __init__(self,color,weight):
    self.color = color
    self.weight = weight
  #class function with self parameter called tree
 def yourfruit(tree):
    print("This class is" , tree.color)
  #class function to add instance attributes
  def number(self, number):
    self.number = number
  #class function to print an initialized attribute value
  def renumber(self):
    print(self.number)
#object declaration or class instantiation
Banana = Fruit("yellow",0.5)
Banana.yourfruit()
Banana.number(10)
Banana.renumber()

Output:

This class is yellow
10

Explanation:

In this example, we have 4 methods. The first method is the __init__ where instance attributes are created. The second one is yourfruit(), this function prints a string with the usage of the color attribute created from the __init__ function. The third function is to add an instance attribute “number”. The fourth is to print the number attribute value assigned using the third function.

Change attribute value

After defining a class with its base attributes, you have the ability to change the attribute’s value. By instantiating an object, access the attribute by writing the object name followed by a dot, attribute name, and an equal sign to the new value. Then the attribute value will be changed. Let’s see the syntax:

Code:

class numbers:
    first = 40
    second = 50

no = numbers()
print(no.first,no.second)
no.first = 60
no.second =70
print(no.first,no.second)

Output:

40 50
60 70

Delete an attribute

Again after declaring an object of the class, you can delete a certain attribute of this class by using the keyword del followed by the object name, dot, and the attribute name. Let’s see the syntax:

Code:

class numbers:
  def __init__(self,first,second):
    self.first = first
    self.second = second

no = numbers(10,20)
print(no.second)
del no.second
print(no.second)

Output:
20
Traceback (most recent call last):
print(no.second)
AttributeError: 'numbers' object has no attribute 'second'

Constructors in Python

Constructors are generated when a class object is created. Constructors are used to assigning values to the class attributes when a class instantiation takes place. And as mentioned in the __init__ section, the __init__ function is considered the constructor in Python. There are two types of constructors in python:

Non parameterized constructor:

This type of constructor doesn’t take any function parameters except the self parameter which indicates class instantiation. Let’s see the syntax:

Code:

class numbers:

  def __init__(self):
    self.first = 10
    self.second = 20
  def print_sum(self):
    self.sum = self.first + self.second
    print(self.sum)
no = numbers()
no.print_sum()

Output:

30

Explanation

As we can see, our constructor here has no any passed parameters. And that resulted in using the default parameters value in the __init__ function when the object is created and one of its functions was called.

Parameterized constructor

This type of constructors takes the self parameter and any other argument required for the application. Let’s see the syntax:

Code:

class numbers:

  def __init__(self,first,second):
    self.first = first
    self.second = second
  def print_sum(self):
    self.sum = self.first + self.second
    print(self.sum)
no = numbers(10,20)
no.print_sum()
no1 = numbers(30,40)
no1.print_sum()

Output:

30
70

Explanation:

As we can see, this constructor has parameters passed to it other than the self parameters. And the result of this implementation is that multiple objects were created out of this class with different values like no & no1, where each one of them has different values for the first & second attributes. Also, we can see how this constructor type implementation affected other class functions results as print_sum().

Destructors in Python

As we have constructors that are created when an object is created. We also have destructors when an object is destroyed or deleted. Why do we need a destructor even though Python has a garbage collector? because it’s not only about the memory used. You might have your program connected to a certain server or a database so you will also need to terminate these processes. Let’s see the syntax:

Code:

class numbers:

  def __init__(self):
    print("Object is instantiated")
  def print_test(self):
    print("is it working?")
  def __del__(self):
    print("Object is deleted")
no = numbers()
no.print_test()
#where the destructor function __del__ is called
del no
no.print_test()

Output:

Object is instantiated
is it working?
Object is deleted

Traceback (most recent call last):
    no.print_test()
NameError: name ‘no’ is not defined
Explanation:

As we can see when the function print_test is called before deleting the object it printed the statement in the function body but when it is called after deleting the object, the program showed a NameError as the object is no longer available to access the class functions.