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.
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.
Class my_class: Statement1 Statement2 .......... .......... Statement_n
class my_class: a = 10 if a < 20: print("This is an example for class")
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.
Once a class is created, then we can create an object for a class.
object_name = class_name()
class my_class: a = 10 b = 20 c = a+b n = my_class() print(n.c)
We can create a function inside a class and call that function with object of the class.
class my_class: a = "Hello" b = "World" def my_fun(c): print(c.a) print(c.b) n = my_class() n.my_fun()
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.
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)
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.
class my_class: def __init__(self): print("Student created") def __del__(self): print("Destructor called, student deleted") my_obj = my_class() del my_obj
Student created Destructor called, student deleted
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 .