Object Oriented Programming or OOP is working with classes and objects. It involves interaction between objects having various attributes.
Python is a object oriented programming language. This means that all the types are representation or instance of a type class.
It is a structure, a blueprint or a building block (a code block) representing or defining the attributes (features and behaviour) of similar parameters.
Using class
keyword.
Name of a class should start with an uppercase letter.
Syntax:
class Class_name
IN [1]
class Students:
roll_no = int()
name = str()
It is an instance of a class.
Syntax:
obj_name = Class_name()
IN [2]
student1 = Students() # creating a new object
student1.roll_no = 1
student1.name = 'Prabhu'
IN [3]
print(student1.name)
print(student1.roll_no)
stdout
Prabhu
1
Calls the attributes for current instance or object.
Syntax:
self.attribute_name
An object is generally defined by the follwing:
The fields
are the variables or containers that store data used and related to an object/Class
Types:
The instance fields are variables that are associated with an object, an instance of the class.
The data they have may vary from object to object and are independent. The field of one instance cannot be accessed by the other.
The instance variables are accessed as follows:
# Inside the class using `self` keyword
self.instance_variable
# Outside the class using the object name
object_name.instance_variable
The class variables are variables that are common throughout the instances of the defined class and can be accessed by all of them.
Modifying data in one object changes it for all the present instances.
They are accessed inside and outside the class definition as follows:
# Using class name to access static variables
Class_name.class_variable
IN [1]
class Student_details:
student_count = 0
def __init__(self, name):
self.name = name # Instance variable
Student_details.student_count += 1 # Class Variable
s = Student_details("Prabhu")
print(s.name) # Instance variable
s1 = Student_details("Mano")
print(s1.name) # Instance variable
print(Student_details.student_count) # Class variable
stdout
Prabhu
Mano
2
The methods
are block of code that, like functions, execute a specific task
Though a method and function are defined in the same way, they have differences.
A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by a name that is associated with an object.
In most respects it is identical to a function except for two key differences:
(remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).
Source: What’s the difference between a method and a function? - StackOverflow
Types:
Instance methods are methods/behavior that are associated with objects. When an object calls one of its instnace methods, the instance method gets implicitly passed object and uses the data it gets with other required parameters to do the task.
Definition and access:
# Definition
def instance_method(self[, ...]): # the self keyword indicates the implicit passing of the object
# Statements
# access inside the class (in another instance method)
self.instance_method(...)
# Access outside the class
obj.instance_method(...)
Note: It is to be noted that an instance method can be called only inside another instance method
A static method is a method that is common for all objects. It is equivalent of function being defined outside the class.
A static method is identified by the decorator @staticmethod
and has implicit object passing using self
keyword.
Definition and Access:
@staticmethod
def class_method([...]):
#Statement(s)
# accessing the method using class name
Class_name.class_method([...])
The static method can be called inside another static method or instance method(s)
A method that executes a set of code whenever a new object/instance is created.
Defined as __new__()
. Generally, this is not defined/overridden and follows the default definition as in the object
class
def __new__(cls, *args, **kwargs):
# Custom constructor
An instance method that initializes the object (instance) created by call with the parameters passed.
The __new__()
method calls this automatically.
Defined as __init__()
.
def __init__(self, *args, **kwargs):
# Statements for object Initialization
IN [7]
class Student:
def __init__(self): # default constructor
self.roll_no = 0
self.name = 'Name'
# print('__init__ file')
def study(self):
print('Studying....')
IN [8]
st1 = Student()
st1.roll_no = 1
st1.name = 'Ravi'
print(f'Roll No: {st1.roll_no}, Name: {st1.name}')
stdout
__init__ file
Roll No: 1, Name: Ravi
IN [2]
class Student_details:
def __init__(self, rn = 0, st_name = 'Name'): # Parametric Constructor
self.roll_no = rn
self.name = st_name
# print('__init__ file')
def study(self):
print('Studying....')
@staticmethod
def work():
print("Working...")
IN [3]
st2 = Student_details(2, 'Rahul')
print(f'Roll No: {st2.roll_no}, Name: {st2.name}')
Student_details.work()
stdout
Roll No: 2, Name: Rahul
Working...
Delete the current instance of class or object. It has default definition in the object Base class
Use __del__()
method to override it
def __del__(self, *args, **kwargs):
# Custom destructor
Start with __
E.g.: __var, __method
It is advised for best programming practice to avoid calling private attributes outside the class.
But if needed, use the following syntax:
obj._classname__attribute
Check the complete example OOPS.py
Ignore the imports. They have been used to provide hinting about the types of each variable