Classes and Objects in Python

Classes and Objects In Python: 

Classes and Objects in Python are the main Property of OOPs.Object-oriented programming (OOPs) is a method of designing a program by binding there related properties and behaviours into individual objects. Here we will discuss, basics of object-oriented programming in Python.  

Example: 

  • Class Abc:  ##class
  • ob1=Abc() ##object 

Let’s understand Classes and objects in Python

Classes and objects in Python

Class:

  • The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods.
  • We can also say that class is a blueprint of an object i.e. if any person is an object, class will have all the information about the structure or behaviour that person.
  • OOPs, reduce the size of our code.
    • To understand the need for creating a class let’s consider an example, let’s say you wanted to track the number of prepsters that may have different attributes like name,user-id, college. If a list is used, the first element could be the Prepster’s name while the second element could represent its user-id and so on. Let’s suppose there are 1000 prepsters, then how would you know which element is supposed to be which? What if we wanted to add another attribute to Prepsters i.e.-Course? This lacks organization and it’s the exact need for classes.

Declaration of Class 

Syntax: 

class ClassName:

 ##body of class 
#python Program
#Rishikesh 
class Prepster
    def __init__(selfname , userid,password):
        self.name=name 
        self.userid=userid 
        self.password=password

Object: 

  • Object is a simple entity which posses some property or behaviour.
  • Everything in Python is an object, and almost everything has attributes and methods. 
  • An object consists of : 

    • State: It is represented by the attributes of an object. It also reflects the properties of an object.
    • Behaviour: It is represented by the methods of an object. It also reflects the response of an object to other objects.
    • Identity: It gives a unique name to an object and enables one object to interact with other objects.
classes and objects

Declaration of Object: 

Synatx: 

class ClassName: 

  ##body of the class  

object_1=ClassName()
#python Program
#Rishikesh 
class Prepster
    def __init__(selfname , userid,password):
        self.name=name 
        self.userid=userid 
        self.password=password
 
ob1=Prepster(‘rishikesh’,‘Abc’,‘[email protected]123’) ##object 
print(ob1.name)

Output: 

rishikesh