Classes and Objects in Python.


Classes in Python:

Class is a logical grouping of related data and methods that operate on them. A class definition starts with the keyword class followed by the name of the class, and a colon. By convention, the first letter of the class name is capitalized. The syntax for a CLASS definition is as follows:

Syntax:
Class Class_Name:
    (Statement_1)
        -
        -
        -
    (Statement-n)
For Example: 

class Employee:    
    id = 10   
    name = "Checks"    
    def display (self):    
        print(self.id,self.name)

Object: 

An object is an entity that holds some state and behaviour. It may be like any real-world entity like birds, car, bike, keyboard, chair etc. Everything in python is an object and almost everything has methods and attributes. A class declaration does not reserve memory at the time of declaration. Memory is allocated when an instance of the class is created. An instance of the class is called an Object.

Creating an instance of a class:

class Employee:    
    id = 10   
    name = "Checks"    
    def display (self):    
        print(self.id,self.name)
emp=Employee()
emp.display()

 

Self:

Here the self is used as reference variable, which refers to the current class object. It is always the first argument in the function definition.

Attributes:

Attributes are the feature of the object or the variables used in the class.

For example: In a class car 

                        speed=240
                        HP=2

Methods:

Methods are the operations or activities performed by the object defined by the class.

For example: In a class car
                    
                        Move()
                        ChangePrice()

Example:

class Student:
    
    def __init__(self,name,DOB,address):
        self.name=name
        self.DOB=DOB
        self.address=address
    def GetName(self):
        print(self.name)
    def Get_DOB(self):
        print(self.DOB)
    def GetAddress(self):
        print(self.address)
Student_Info=Student("John","07/07/1997","Mumbai")
Student_Info.GetName()
Student_Info.Get_DOB()
Student_Info.GetAddress()

 

Post a Comment

0 Comments