Skip to main content

OOPs in Python in Hindi (Part -14)

Subscribe

* indicates required
        OBJECT ORIENTED PROGRAMMING

Python ek object oriented programming language hai, iska mtlb ye hai ki Python mai hr ek chiz object hai. Dekho Oops kafi confusing ho skta hai agar ap longo ko oops kafi gande tarike se padhya gya hai , mai is post ke jariye ap longo ko oops ko bahut assan shabdo mai samjhane ki pori koshish krunga. 
Aayiye oops padhne se pehle kuch terms clear kr lete hai , taki ap longo ko ise padhne mai koi muskil na ho.

Class and object

Class ek design ya blueprint hai. Object ek real thing hai.
Aayiye ise example ki madad se aur clear krte hai jaise Animal ek class hai aur cat , dog , tiger etc ye sb object hai, Animal ek real chiz nhi hai lekin object ek real chiz hai


Java Class and Object: Object-Oriented Programming

Ek example aur lete hai jaise bhot longo ke pass iPhone 11 hoga lekin ye design sirf ek baar hi kiya jata hai to ek class ke pass kai object ho skte hai.
Aayiye object ko aur deep se samjhte hai
Jaise...

mylist = [ 3,5,6,7]

to hm yaha kahenge ki mylist ek object hai class list ka , lekin ye jo list class hai ye built in class hai, hm yaha khud ki class bana skte hai jise hm user-defined class kahenge.

Object kya hai ?

Object ek real chiz hai, object ke pass attribute aur behaviour hota hai, attribute is like how we look , what we wear ,basically ise variables kahte hai behaviour hamare action ko define krta hai like walking , talking , sleeping etc. ise hm methods kah skte hai.
Function inside a class is called method

                                                         What is Class and Object in Java OOPS?

User defined class

Class ko create krne ke liye hme class keyword ka use krna padta hai
Example:
---------------------------------------------------------------------------------
#creating a  class

class Computer:
    def config(self):
        print("i5 , 16gb , 1TB")

#creating an object

com1= Computer()

#Calling an object

Computer.config(com1)

Ouptut:
i5 , 16gb , 1TB


#class ko hm create krte hai class keyword ki madad se
#config yaha ek method hai
#com1 name ka hmne ek object create kiya hai
#Aur fir hmne ise call kiya hai , call krte samay hm kr kya rahe hai ki hmne self(argument) mai com1 name ka parameter pass kiya hai
#Self keyword ki madad se hm kisi bhi python class ke attributes aur method ko acess kr skte hai
#It is good programming practice to start the class name with capital letter

#Another way of calling an object

com1.config()

Output:
i5,16gb 1tb

------------------------------------------------------------- 
# Another way of doing this same program

class computer:
    def config(self):
        print("i5,16gb 1tb")

com1 = computer()
com1.config()

Output:
i5,16gb 1tb
------------------------------------------------------------------------------------

                    __init__ Method

init stand for intialization , init method ka use hota hai variable ko intialize krne ke liye , init method ki speciality ye hai ki ise hme call nhi krna padta hai ye automatically call ho jati hai object create krte samay.
Let's take an example
------------------------------------------------------------
 class grow:
    def __init__(self):
        print("in init")
    def config(self):
        print("hello")

com1 = grow()
com1.config()

Output:
in init
hello

#To ap dekh skte hai ki init method ko hame call nhi krna padta , ye automatically call ho jati hai object create krte samay, ye java ke constructor se kafi similar hai.
-----------------------------------------------------------
class Computer:
    def __init__(self, cpu, ram):
        self.cpu = cpu #intializing the value 
        self.ram = ram
    def config(self):
        print(self.cpu , self.ram)

com1 = Computer('i5' ,16)
com2 = Computer('Ryzen 3' ,8)
com1.config()
com2.config()

#Output:
i5 16
Ryzen 3 8

# Self parameter basically hr method ka first parameter hota hai, Self name jruri nhi hai hm koi bhi name use kr skte hai lekin most commanly self use hota hai becoz it increase the code readability
#Self ka use basically variable ko access krne krne ke liye hota hai jo ki us particular class ko belong krte hai.
----------------------------------------------------------
class BadmintonPlayer():
     def __init__(self,aName,aRacket,aShuttle):
        print('I m in Constr...')
        self.name = aName
        self.racket = aRacket
        self.shuttle = aShuttle


sindhu = BadmintonPlayer('Sindhu','Yonex','Yonex')

Output:
I m in Constr...
--------------------------------------------------------------------------------------
class Person():
    def __init__(self,aName):
        print('I m in Constructor')
        self.name = aName
    def eat(self):
        print('Idly')
    def play(self):
        print('Badminton')

        print('or Cricket')
    def exercise(self):
        print('Jogging')

p1 = Person('Sai')

p1.eat()
p1.play()
p1.exercise()
p1.name

Output:
I m in Constructor
Idly
Badminton
or Cricket
Jogging
'Sai'

#p1.name , basically yaha hm attribute ko acess krne ki koshish kr rahe hai isliye hmne yaha parenthesis() nhi lagaya

# har method ki first parameter mai hmne self isliye likha hai kyoki hm us self mai P1 parameter pass kr rahe hai jo ki hamara object hai

#Agar ap self parameter nhi likhoge to at the time of calling ap ko error milegi
---------------------------------------------------------------------------------


 class CricketPlayer():
    def __init__(self,anAge,aName):
        self.name = aName
        self.age = anAge
        self.awards = list()

sachin = CricketPlayer('Sachin','46')


sachin.awards.append("Bharat ratn")
sachin.awards

Output:

['Bharat ratn']


#Nice one
----------------------------------------------------------
class CricketPlayer():
    def __init__(self,anAge,aName):
        self.name = aName
        self.age = anAge
        self.awards = list()
        self.jerseys = ('White','Blue')
        self.jerseyNums = {'White': 10,'Blue':10}
        self.records = set(['Highest Score','Num of Matches'])

sachin = CricketPlayer('Sachin','46')
sachin.records


Output:

{'Highest Score', 'Num of Matches'}
---------------------------------------------------------

class Person():
    instName = 'SaiIT' #class variable
    def __init__(self,pwd,aName):
        self.psswrd = pwd   #instance variable
        self.name = aName   #instance variable

p1 = Person('Password','Sai')
p2 = Person('P2','Shreyas')
p1.instName


Output:
'SaiIT'


#Yaha hmne class variable ko access kiya hai
-------------------------------------------------------------------------------------

class CricketPlayer():
    countryName = 'India'
    def __init__(lavanya,aName, aBat, aBall):
        lavanya.name = aName
        lavanya.bat = aBat
        lavanya.ball = aBall
jo = CricketPlayer('ram' ,'guru', 'guru')

jo.name


Output:

'ram'

# To ap dekh skte hai hm self ki jagah kuch bhi use kr skte hai , hmne yaha lavanya use kiya lekin mostly self use hota hai kyoki ye code readability ko badha deta hai.
---------------------------------------------------------

Public , Protected and Private attribute


Public attributes ko hm inside the class or outside the class kahi bhi access kr skte hai

Syntax:

name = "rishabh"

Protected attribute ko hm within a class access kr skte 
hai aur sub class mai bhi access kr skte hai

Syntax:

_name = "rishabh"


Private attribute ko hm sirf within a class access kr skte hai.

Syntax:

__name = "rishabh"


Example:

--------------------------------------------------------
class Person:
    

    def __init__(self):
        self.__passwd = 'I am Private'
        self._petName = 'I am Protected'
        self.name = 'I am Public'

ob = Person()
ob.name

Output:
'I am Public'


ob._petName

Output:
'I am Protected'



ob.__passwd

Output:

error


#Error, becoz private variable ko outside the class access nhi kr skte


--------------------------------------------------------

                Private method

Private method ko hm outside the class access nhi kr skte or na hi hm ise sub class mai access kr skte hai.

Example:

---------------------------------------------------------

class Bank:
    def __deposit(self):
        print('Deposited Money.')
    def __withdraw(self):
        print('Withdrawal Done.')

hdfc = Bank()
hdfc.__deposit()

Output:

error

#Error , becoz outside the class access nhi kr skte 

----------------------------------------------------------

Static method


Static method basically ek simple function hai jisme self argument use nhi hota


Example:

---------------------------------------------

class Person:
    @staticmethod
    def study(): 
        print('DS')

Person.study()

Output:

DS


#Ise hm class ke through bhi call kr skte hai is liye ise ham static method or class method bhi kahte hai.
-----------------------------------------------------


Pillar of OOPs 

1.Encapsulation


2.Inheritance




                       Encapsulation

Encapsulation ki madad se hm kisi bhi object ke component ke accessibility ko restrict kr skte hai, aisa hm getter or setter method ki help se krte hai, aur agar dusro shabdo mai kahe to the process of getting the getter and setter method is called encapsulation.

Aaiye ise example ki madad se aur clear kre 

---------------------------------------------------------- 

class Person():
    def __init__(self,pwd,aName):
        self.__psswrd = pwd

        self.name = aName
    def getPsswrd(self):
        return self.__psswrd

p1 = Person('Passbhrth','Sai')

p1.getPsswrd()


Output:

'Passbhrth'


#Ap dekh skte hai ki sbse pahle hm Password ko private kr de rahe hai , fir hm ek method ka use kr rahe hai us private variable ko access krne ke liye , so basically this process is called encapsulation.
-------------------------------------------------------



class Person():
    def __init__(self,pwd,aName):
        self.__psswrd = pwd
        self.name = aName
    def getPsswrd(self,aUsrName):
        if(aUsrName=='Sai'):
            return self.__psswrd
        else:
            return 'None'
    def setPswrd(self,newPswrd):
        self.__psswrd = newPswrd

p1 = Person('Passbhrth','Sai')



p1.__psswrd

Ouput:
error

p1.getPsswrd('Sai')

Output:
'Passbhrth'

p1.setPswrd('Rishabh')
p1.getPsswrd('Sai')

Output:

'Rishabh'


#Is process ko hm encapsulation kahte hai , the process of using getter and setter method is called encapsulation

----------------------------------------------------------

                 Inheritance

Inheritance kya hai aur iski jrurt kyo padi, aaiye example ki madad se samjhte hai ki inheritance ki jrurt kyo padi


-----------------------------------------------------------
#without inheritance


class SportsPlayer():
    def __init__(self,playerName,playerAge):
        self.name = playerName
        self.age = playerAge

class BadmintonPlayer():

    def __init__(self,playerName,playerAge,racquetName,shuttleName):
        self.name = playerName
        self.age = playerAge
        self.racquet = racquetName
        self.shuttle = shuttleName


class CricketPlayer():
    def __init__(self,playerName,playerAge,batName,ballName):
        self.name = playerName
        self.age = playerAge
        self.bat = batName
        self.ball = ballName



sai = SportsPlayer('Sai',34)
sindhu = BadmintonPlayer('Sindhu',16,'Yonex','Yonex')
sachin = CricketPlayer('Sachin',18,'MRF','MRF')


To ap yaha dekh skte hai ki sari classes mai name aur age common hai , hm baar - baar name aur age ko repeat kr rahe hai , hm inhe repeat krne ke bajaye inhe inherit kr skte hai,aur is process ko inheritance kahte hai, aur isliye hme inheritance ki jrurt padi
to SportsPlayer ko hm super class kahenge aur BadmintonPlayer or CricketPlayer ko hm derived class kahenge kyoki derived class super class ki property ko inherit krti hai.
-------------------------------------------------
# with inheritance

class SportsPlayer():
    def __init__(self,playerName,playerAge):
        self.name = playerName
        self.age = playerAge



class BadmintonPlayer(SportsPlayer):
    def __init__(self,playerName,playerAge,racquetName,shuttleName):
        SportsPlayer.__init__(self,playerName,playerAge)
        self.racquet = racquetName
        self.shuttle = shuttleName

sindhu = BadmintonPlayer('Sindhu',24,'Yonex','Yonex')


class CricketPlayer(SportsPlayer):
    def __init__(self,playerName,playerAge,batName,ballName):
        SportsPlayer.__init__(self,playerName,playerAge)
        self.bat = batName
        self.ball = ballName

------------------------------------------------------------------------------------------

Inheritance ki madad se hm code ko doobara re-use kr skte
 hai aur aur ye program ki  complexity ko kam kr deta hai.






                                        



Comments

Python tutorial in hindi

Python Introduction in Hindi (Part -1)

Subscribe * indicates required Email Address *                                                PYTHON                                                                                                                                                               Python kya hai ? Python ek programming language h , to programming language kya h , dekho agar mai kisi se baat kr rha hu ya fir kisi ko kuch samjha raha hu to usse baat krne ya samjhane m mujhe kisi language ka use krna padega jaise man lo mai use hindi m samjha rha hu to yaha mai hindi language use kr rha hu  thik usi tarah computer ko samjhane ke liye mujhe kisi programming language ka use krna padega , aur PYTHON unme se ek hi hai. "  agar ap ko lagta h ki python language ka naam  python( ajgar ) ke naam pr rakha gya h to ap bahut badi galat fahmi mai ji rhe ho kyoki python ka naam ek comedy group 'montey python' se liya gya h" Python hi kyo ? Py

Modules and Packages in Python in Hindi (Part -16)

                    Modules and Packages Modules aur Packages sunne mai kafi fancy term lag raha hai, lekin is post ko padhne ke baad apko clear hojayega ki modules aur packages kya hai ? let's suppose apne ek python program banaya aur usse save kr diya rishabh.py name se, aur fir apne ek dusra program banaya aur ussse save kr diya gupta.py name se , to basically rishabh.py ek module ho gya aur ussi tarah gupta.py bhi ek module ho gya aur har module ke andar kuch classes hongi kuch , kuch functions honge , aur ham in classes or function ka use kr skte hai dusre program mai import statement ki madad se jo ki hm aange dekhne wale hai , to basically module .py name se save koi bhi python program hogaya, to ab baat krte hai ki packages kya hote hai , to packages basically collection of modules and empty __init__.py file hote hai, to agar upar wala example le to agar hm rishabh.py , gupta.py aur empty __init__.py file ko ek folder mai rakhe to vo folder ek Package kahelayega. module - r

Python Strings in hindi (Part -6)

Subscribe * indicates required Email Address *                                                 String in Python Python mai hm string ka use krte hai text information ko store krne ke liye jaise ki name, jaisa ki hm jante hai Python mai character nhi hota python mai character ko string of length one mana jata hai. String ko single quotation mai bhi represent kr skte hai aur double quotation mai bhi represent kr skte hai. Let's see an example..    print('hey') print("hey") agar hame multiline string ko assign krna hai to ham wo bhi kr skte hai example: a =  "" "hey, this is rishabh gupta and I will teach you python from scratch  enjoy the blog" "" print (a) output hey, this is rishabh gupta and I will teach you python from scratch  enjoy the blog Python ki string ek array jaise hoti hai iska mtlb ye hua ki hm python string ki indexing kr skte hai (indexing krne ka mtlb hua po

Data Structure in Python in hindi (Part -7)

Subscribe * indicates required Email Address *                                                 Python Data Structure A  data structure  is a collection of different forms and different  types  of  data  that has a set of specific operations that can be performed Python mai data structure two categories mai divided hai pahla hai built in data structure (built in ka mtlb hai jo ki python ke undar hi hai hame inhe bahar se import krke lane ki koi jrurt nhi hai, aur dusra hai user defined data structure , is post mai hm python ke built in data structure ki baat krenge.                                                                                        Built-in Data Structure Lists Dictionary Tuple Set 1.Lists List basically ek container hai jisme hm bahut saare object rakh skte hai , List mai hm textual data aur numerical data dono rakh skte hai, chaliye ise aur clear banate hai ek example ki madad se , es example ko samajhne

Python Variables in hindi (Part -3)

Subscribe * indicates required Email Address *                                                 Variables Variable basically ek container hota hai jisme ap data value store krte ho . example a = "hello" b = 3 c = 3.4 To idhar ap dekh skte hai  a, b, c ye teeno variable hai , a mai hmne hello naam ki string ko store kiya hai , b mai hmne 3 ko store kiya hai aur c m hamne 3.4 ko store kiya hai ap ise aise bhi samjh skte ho ki (a) ek box h  jyisme hmne hello ko daal diya hai , i hope ki apko variable bahut acche se clear ho gya hoga.  Waise mai apko bta du ki baki programming language jaise java waha hme variable ko declare krna padta hai mtlb hme batana padta hai ki ye variable kis type ka hai jaise int , float , string, char etc. lekin python mai hme yaha batana nhi padta ki ye kis type ka hai. Int , float , string , char ka use kaha hota h let's see   inka use in value ko store krne mai hota hai. Jaise ki maine

Python for loop and while loop in hindi (Part -10)

Subscribe * indicates required Email Address *                            For loops For loop iteration ke liye use hota hai , iteration ka dusra mtlb ho skta hai repetition , agar mai poochu ki kis chiz pe iteration to answer hai , iteration over a sequence like string, list , dicitionary , tuple , sets. Syntax: for iterator_name in iterating_sequence:        Statement...... Aayiye ise example ki madad se aur clear krte hai....... ------------------------------------------------------------------------------------------ #program of for loop in string r = 'rishabh' for x in (r): print (x) output: r i s h a b h ------------------------------------------------------------------------ #program to print items in list l =[ "ram" , "shyam" , "rishabh" , "shyamlal" ] for y in l: print (y) Output: ram shyam rishabh shyamlal # Ap dekh skte hai ki kaise ye loop work kr rha hai, h

Python Syntax and Comments in Hindi (Part -2)

Subscribe * indicates required Email Address *                    Python Syntax Chalo surwat krte h dosto agar man lo apko apna naam print krana h ya fir kuch bhi print karana hai python mai to kaise kroge  , so answer is by using a print statement , jaise mera naam Rishabh Gupta hai aur mujhe  mera naam print karana hai                                     >>> print("Rishabh Gupta")                                              Rishabh Gupta    "  maine yaha double inverted comma use kiya h ap single inverted comma ya triple inverted comma bhi use kr skte ho"                               >>> print('Rishabh Gupta')                                                 Rishabh Gupta                                         >>> print('''Rishabh Gupta''')                                                   Rishabh Gupta " ye code maine Python 3.7.5 shell

Error and Exception Handling in Python in Hindi (Part -15)

Subscribe * indicates required Email Address *                                         Error and Exception Handling Python mai coding krte samay kabhi na kabhi apko error to jrur mili hogi jaise print('hello) Output: Syntax error 2+'s' Output: Type error So is tarah ki error jo python nhi samajh pa raha hai ise hm exception kahte hai. Hm is tarah ke exception ko handle kr skte hai, dekho hota kya hai jb exception aati hai to python interpreter program ko stop kr deta hai  aur error throw kr deta hai, aur hame output mai error mil jati hai , to hm error ko handle kr skte hai try aur except keyword ka use kr ke  so , try aur except error ko handle krte hai aur baki ke code ko continue rakhne mai madad krte hai. So , jb bhi apko lage ki yaha error hone ke chances hai ise try keyword ke andar rakhe, aur us exception ki handling hm except ke andar  rakhenge Aayiye ise example ki madad se aur clear krte hai... -----

Functions in Python in hindi (Part -13)

Subscribe * indicates required Email Address *                              Functions Function ek block of code hota hai jo ki us code se related operation perform krta hai. Python mai  kafi saare built in function hai jaise print(), input(), file(), int() etc , pr aap yaha khud ka function bhi create kr skte ho jise ham user - defined function kahenge. Function ko create krne ke do steps hai pehla hai defining a function or dusra hai Calling the function. Python function ko hm define krte hai def keyword ki madad se. Syntax: #Defining a function -step 1  def name(parameter1, parameter2,....parameterN):               Statement                return #Callling a function - step 2 name() Function ki jrurt kyo padi ? Function basically duplication of code ko reduce krta hai , jaise agar maan lo ki apko kuch block of code ki jrurt hai, aur usi program mai apko us block of code ki doobara jrurt hai , to apko baar baar wahi code d