Python Classes and Objects

Object Oriented Programming is most widely used programming paradigm and almost it provides a way to create and manage Objects.

Python is an object oriented programming language. python provide a keyword called class to create an Object. Everything in a python is an object with its methods, a class is like an object constructor.

Creating Classes

In python, a class is defined by using the keyword class. Every class has a unique name followed by a colon(:). A class can be defined anywhere in a python program.

Syntax

Class my_class:
 Statement1
 Statement2
 ..........
 ..........
 Statement_n

Example:

class my_class:
 a = 10
 if a < 20:
  print("This is an example for class")

Output:

This is an example for class

Note: Variables which are defined inside a class is known as class variables and functions which are defined inside a class is known members of class.

Creating Objects

Once a class is created, then we can create an object for a class.

Syntax

object_name = class_name()

Example:

class my_class:
 a = 10
 b = 20
 c = a+b

n = my_class()
print(n.c)

Output:

30

We can create a function inside a class and call that function with object of the class.

Example:

class my_class:
 a = "Hello"
 b = "World"

 def my_fun(c):
  print(c.a)
  print(c.b)

n = my_class()
n.my_fun()

Output:

Hello
World

__init__() Function

All classes have a function called __init__(). When a class is initiated the __init__() function will be executed. The __init__() function is similar to constructors in C++ and Java. Constructor is a special function that is automatically executed when an object of a class is created.

Example:

class my_class:
 def __init__(self, a, b):
  self.a = a
  self.b = b

n = my_class("Python", "Tutorial")

print(n.a)
print(n.b)

Output:

Python
Tutorial

__del__() Function

The __del__() method is a known as a destructor method in Python. Destructors are called when an object gets destroyed. In python destructors are not needed because python has a garbage collector that handles memory management automatically.

Example:

class my_class:

    def __init__(self):
        print("Student created")

    def __del__(self):
        print("Destructor called, student deleted")

my_obj = my_class()
del my_obj

Output:

Student created
Destructor called, student deleted

More Reading

Post navigation

1 Comment

  • Hello my loved one! I wish to say that this article is awesome, nice written and come with almost all significant infos. I?¦d like to see extra posts like this .

Leave a Reply

Your email address will not be published. Required fields are marked *