IKH

Types of Variables

  • Inside python class three types of variables are allowed:
    • Instance variables (Object level variables)
    • Static variables (Class level variables)
    • Local variables (Method level variables)

Instance Variables

  • If the value of a variable is varied from object to object, then such type of variables are called instance variables.
  • For every object a separate copy of instance variables will be created.
  • We can declare instance variables:
    • Inside constructor by using self variable.
    • Inside Instance method by using self variable.
    • Outside of the class by using object reference variable.

Inside Constructor

  • We can declare instance variables inside a constructor by using self keyword. Once we creates object, automatically these variables will be added to the object.

Example

Python
class Employee:
    def __init__(self):
        self.eno=10
        self.ename='Amit'
        self.esal=100
 
e=Employee() 
print(e.__dict__)

Output

PowerShell
{'eno': 10, 'ename': 'Amit', 'esal': 100}

Inside Instance Method

  • We can also declare instance variables inside instance method by using self variable. If any instance variable declared inside instance method, that instance variable will be added once we call that method.

Example

Python
class Test:
    def __init__(self):
        self.a=100
        self.b=200
 
    def m1(self):
        self.c=300

test=Test()
test.m1()
print(test.__dict__)

Output

PowerShell
{'a': 100, 'b': 200, 'c': 300}

Outside of the class

  • We can also add instance variables outside of a class to a particular object using object reference variable.
Python
class Test:
    def __init__(self):
        self.a=100
        self.b=200
 
    def m1(self):
        self.c=300

test=Test()
test.m1()
test.d = 400
print(test.__dict__)

Output

PowerShell
{'a': 100, 'b': 200, 'c': 300, 'd': 400}

How to access Instance variables

  • We can access instance variables with in the class by using self variable and outside of the class by using object reference.

Example

Python
class Test: 

def __init__(self): 
self.a=10 
self.b=20 
 
def display(self): 
print(self.a) 
print(self.b) 
 
t=Test() 
t.display() 
print(t.a,t.b) 

Output

PowerShell
10
20
10 20

How to delete instance variable from the object

  • Within a class we can delete instance variable as follows del self.variableName.
  • From outside of class we can delete instance variables as follows del objectreference.variablename.

Example

Python
class Test: 
def __init__(self): 
self.a=10 
self.b=20 
self.c=30 
self.d=40 
def m1(self): 
del self.d 
 
t=Test() 
print(t.__dict__) 
t.m1() 
print(t.__dict__) 
del t.c 
print(t.__dict__)

Output

PowerShell
{a: 10, b: 20, c: 30, d: 40}
{a: 10, b: 20, c: 30}
{a: 10, b: 20}

Note

  • The instance variables which are deleted from one object,will not be deleted from other objects.

Example

Python
class Test: 
def __init__(self): 
self.a=10 
self.b=20 
self.c=30 
self.d=40 
 
 
t1=Test() 
t2=Test() 
del t1.a 
print(t1.__dict__) 
print(t2.__dict__)

Output

PowerShell
{b: 20, c: 30, d: 40}
{a: 10, b: 20, c: 30, d: 40}
  • If we change the values of instance variables of one object then those changes wont be reflected to the remaining objects, because for every object we are separate copy of instance variables are available.

Example

Python
class Test: 
def __init__(self): 
self.a=10 
self.b=20 
 
t1=Test() 
t1.a=888 
t1.b=999 
t2=Test() 
print('t1:',t1.a,t1.b) 
print('t2:',t2.a,t2.b)

Output

PowerShell
t1: 888 999
t2: 10 20

Static variables

  • If the value of a variable is not varied from object to object, such type of variables we have to declare with in the class directly but outside of methods. Such type of variables are called static variables.
  • For total class only one copy of static variable will be created and shared by all objects of that class.
  • We can access static variables either by class name or by object reference. But recommended to use class name.

Instance Variable vs Static Variable

Note

  • In the case of instance variables for every object a seperate copy will be created,but in the case of static variables for total class only one copy will be created and shared by every object of that class.

Example

Python
class Test: 
x=10 
def __init__(self): 
self.y=20 
 
t1=Test() 
t2=Test() 
print('t1:',t1.x,t1.y) 
print('t2:',t2.x,t2.y) 
Test.x=888 
t1.y=999 
print('t1:',t1.x,t1.y) 
print('t2:',t2.x,t2.y) 

Output

PowerShell
t1: 10 20
t2: 10 20
t1: 888 999
t2: 888 20

Various places to declare static variables

  • In general we can declare within the class directly but from out side of any method.
  • Inside constructor by using class name.
  • Inside instance method by using class name.
  • Inside classmethod by using either class name or cls variable.
  • Inside static method by using class name.

Example

Python
class Test: 
a=10 
def __init__(self): 
Test.b=20 
def m1(self): 
Test.c=30 
@classmethod 
def m2(cls): 
cls.d1=40 
Test.d2=400 
@staticmethod 
def m3(): 
Test.e=50 
print(Test.__dict__) 
t=Test() 
print(Test.__dict__) 
t.m1() 
print(Test.__dict__) 
Test.m2() 
print(Test.__dict__) 
Test.m3() 
print(Test.__dict__) 
Test.f=60 
print(Test.__dict__)

Output

PowerShell
5

How to access static variables

  • inside constructor: by using either self or classname.
  • inside instance method: by using either self or classname.
  • inside class method: by using either cls variable or classname.
  • inside static method: by using classname.
  • From outside of class: by using either object reference or classnmae.

Example

Python
class Test: 
a=10 
def __init__(self): 
print(self.a) 
print(Test.a) 
def m1(self): 
print(self.a) 
print(Test.a) 
@classmethod 
def m2(cls): 
print(cls.a) 
print(Test.a) 
@staticmethod 
def m3(): 
print(Test.a) 
t=Test() 
print(Test.a) 
print(t.a) 
t.m1() 
t.m2() 
t.m3() 

Output

PowerShell
5

Where we can modify the value of static variable

  • Anywhere either with in the class or outside of class we can modify by using classname. But inside class method, by using cls variable.

Example

Python
class Test: 
a=777 
@classmethod 
def m1(cls): 
cls.a=888 
@staticmethod 
def m2(): 
Test.a=999 
print(Test.a) 
Test.m1() 
print(Test.a) 
Test.m2() 
print(Test.a) 

Output

PowerShell
777
888
999

If we change the value of static variable by using either self or object reference variable

  • If we change the value of static variable by using either self or object reference variable, then the value of static variable wont be changed,just a new instance variable with that name will be added to that particular object.

Example

Python
class Test: 
a=10 
def m1(self): 
self.a=888 
t1=Test() 
t1.m1() 
print(Test.a) 
print(t1.a) 

Output

PowerShell
10
888

Example

Python
class Test: 
x=10 
def __init__(self): 
self.y=20 
 
t1=Test() 
t2=Test() 
print('t1:',t1.x,t1.y) 
print('t2:',t2.x,t2.y) 
t1.x=888 
t1.y=999 
print('t1:',t1.x,t1.y) 
print('t2:',t2.x,t2.y) 

Output

PowerShell
t1: 10 20
t2: 10 20
t1: 888 999
t2: 10 20

Example

Python
class Test: 
a=10 
def __init__(self): 
self.b=20 
def m1(self): 
self.a=888 
self.b=999 
 
t1=Test() 
t2=Test() 
t1.m1() 
print(t1.a,t1.b) 
print(t2.a,t2.b) 

Output

PowerShell
888 999
10 20

Example

Python
class Test: 
a=10 
def __init__(self): 
self.b=20 
@classmethod 
def m1(cls): 
cls.a=888 
cls.b=999 
 
t1=Test() 
t2=Test() 
t1.m1() 
print(t1.a,t1.b) 
print(t2.a,t2.b) 
print(Test.a,Test.b)

Output

PowerShell
888 20
888 20
888 999

How to delete static variables of a class

  • We can delete static variables from anywhere by using the following syntax del classname.variablename
  • But inside classmethod we can also use cls variable del cls.variablename

Example

Python
class Test: 
a=10 
@classmethod 
def m1(cls): 
del cls.a 
Test.m1() 
print(Test.__dict__) 

Output

PowerShell
9

Example

Python
class Test: 
a=10 
def __init__(self): 
Test.b=20 
del Test.a 
def m1(self): 
Test.c=30 
del Test.b 
@classmethod 
def m2(cls): 
cls.d=40 
del Test.c 
@staticmethod 
def m3(): 
Test.e=50 
del Test.d 
print(Test.__dict__) 
t=Test()
print(Test.__dict__) 
t.m1() 
print(Test.__dict__) 
Test.m2() 
print(Test.__dict__) 
Test.m3() 
print(Test.__dict__) 
Test.f=60 
print(Test.__dict__) 
del Test.e 
print(Test.__dict__) 

Output

PowerShell
7

Note

  • By using object reference variable/self we can read static variables, but we cannot modify or delete.
  • If we are trying to modify, then a new instance variable will be added to that particular object. t1.a = 70
  • If we are trying to delete then we will get error.

Example

Python
class Test: 
a=10 
 
t1=Test() 
del t1.a ===>AttributeError: a 

Output

PowerShell
6
  • We can modify or delete static variables only by using classname or cls variable.
Python
import sys 
class Customer: 
''''' Customer class with bank operations.. ''' 
bankname='DURGABANK' 
def __init__(self,name,balance=0.0): 
self.name=name 
self.balance=balance 
def deposit(self,amt): 
self.balance=self.balance+amt 
print('Balance after deposit:',self.balance) 
def withdraw(self,amt): 
if amt>self.balance: 
print('Insufficient Funds..cannot perform this operation') 
sys.exit() 
self.balance=self.balance-amt 
print('Balance after withdraw:',self.balance) 
 
print('Welcome to',Customer.bankname) 
name=input('Enter Your Name:') 
c=Customer(name) 
while True: 
print('d-Deposit \nw-Withdraw \ne-exit') 
option=input('Choose your option:') 
if option=='d' or option=='D': 
amt=float(input('Enter amount:')) 
c.deposit(amt) 
elif option=='w' or option=='W': 
amt=float(input('Enter amount:')) 
c.withdraw(amt) 
elif option=='e' or option=='E': 
print('Thanks for Banking') 
sys.exit() 
else: 
print('Invalid option..Plz choose valid option') 

Output

PowerShell
D:\durga_classes>py test.py
Welcome to DURGABANK
Enter Your Name:Durga
d-Deposit
w-Withdraw
e-exit
Choose your option:d
Enter amount:10000
Balance after deposit: 10000.0
d-Deposit
w-Withdraw
e-exit
Choose your option:d
Enter amount:20000
Balance after deposit: 30000.0
d-Deposit
w-Withdraw
e-exit
Choose your option:w
Enter amount:2000
Balance after withdraw: 28000.0
d-Deposit
w-Withdraw
e-exit
Choose your option:r
Invalid option..Plz choose valid option
d-Deposit
w-Withdraw
e-exit
Choose your option:e
Thanks for Banking

Local variables

  • Sometimes to meet temporary requirements of programmer,we can declare variables inside a method directly,such type of variables are called local variable or temporary variables.
  • Local variables will be created at the time of method execution and destroyed once method completes.
  • Local variables of a method cannot be accessed from outside of method.

Example

Python
class Test: 
def m1(self): 
a=1000 
print(a) 
def m2(self): 
b=2000 
print(b) 
t=Test() 
t.m1() 
t.m2() 

Output

PowerShell
1000
2000

Example

Python
class Test: 
def m1(self): 
a=1000 
print(a) 
def m2(self): 
b=2000 
print(a) #NameError: name 'a' is not defined 
print(b) 
t=Test() 
t.m1() 
t.m2() 

Output

PowerShell
7

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error