CLASS,OBJECT -PYTHON 2022

  • CLASS:

Class is a logical entity. It contains logics of the application. Class is a  blueprint, for single class, We can create  multiple objects. We can create a class with class keyword.

  • OBJECT :

Object is a physical entity. It represents memory.

  • Self is a qualifier.

Ex-1:

class Myclass() :

def add(self, a, b) :

   print(a+b)

a=Myclass()     [object created]

a=add(10,20)    #30 [function calling]

 

 

  • LOCAL VARIABLES :

Variables which are declared inside the function/method/constructor is called “Local variables”.

  • SCOPE/SPAN/LIFE OF LOCAL VARIABLES :

Scope of local variables is within the function/method.

Ex-1:

class Myclass() :

 def add(self) :

     a=10

     b=20

     print(a+b)  #30

  def sub(self) :

        print(a-b)  #ERROR

c=Myclass()

c.add()

c.sub()

 

  • INSTANCE VARIABLES/CLASS VARIABLES :

Variables which are declared inside the class but outside the method. is called “Instance variable”. If instance variable name and local variable name is same then we can access instance carriable with self. Root class for all python classes is “Object“ class within the function.

 

  • SCOPE OF INSTANCE VARIABLE :

The scope of class variable is throughout the class only for methods.

Ex-1:

class Myclass() :

x=100

y=200

def add(self, a, b) :

   print(self.x+self.y)  #300

   print(a+b)   #12

def sub(self, a, b) :

   print(self.x-self.y)  #-100

   print(a-b)  #7

def mul(self, a, b) :

   print(self.x*self.y)  #20000

   print(a*b)  #40

c=Myclasss()

c.add(10, 2)

c.sub(10 ,3)

c.mul(10,4)

 

Ex-2:

class Myclass() :

a=100

b=200

def add (self, a,b):

print(self.a+self.b)

print(a+b)

def sub(self,a ,b) :

print(self.a-self.b)

print(a-b)

def mul(self, a, b):

print(self.a*self.b)

print(a*b)

c=Myclass()

print(c.a)  #100

print(c.b)   #200

 

 

  • GLOBAL VARIABLES :

The variables which are declared outside of the class are called “ global variables”. The scope of global variables is throughout the program.

Ex-1:      
x=1000

y=1000

class Myclass():

a=100

b=200

def add (self, a, b):

  print(self.a+self.b)

  print(a+b)

  print(x+y)

def sub(self, a, b):

  print(self.a-self.b)

  print(a-b)

  print(x-y)

def mul(self, a, b) :

    print(self.a*self.b)

    print(a*b)

c=Myclasss()

c.add()

c.sub()

c.mul()

print(c.a, c.b)   
print(x+y)

Related Posts