The concept of allocating memory space for non-static variable of a
class at runtime dynamically is known as an object. We can create ‘n’ number of objects for one class.
After creating the object, address of object will be stored in variable and we
call that variable as a reference variable. From that variable we can put the
data into object, we can get data and also call the methods on that object.
Example –
def display(): print 'hi' class X: def __init__(self,i,j): self.i=i self.j=j def display(self): print self.i print self.j X1=X(100,400)
print X1
print id(X1)
print hex(id(X1)).upper() X1.display() X2=X(200,500)
print X2
print hex(id(X2)).upper() X2.display() display()
Output –
<__main__.X instance at 0x02623288>
39989896
0X2623288
100
400
<__main__.X instance at 0x026232B0>
0X26232B0
200
500
hi
Example –
Example –
class InsufficientFund(Exception): """ balance not available """
class Customer: cbname='sbi' def __init__(self,cname,cadd,cacno,cbal): self.cname=cname self.cadd=cadd self.cacno=cacno self.cbal=cbal def deposit(self,damt): self.cbal=self.cbal+damt def withdraw(self,wamt): if wamt>self.cbal: raise InsufficientFund self.cbal = self.cbal - wamt def display(self): print self.cname print self.cadd print self.cacno print self.cbal print self.cbname C1=Customer('rakesh','guwahati',8001,100000.00) C1.display() C1.deposit(10000.00)
try: C1.withdraw(70000.00)
except: print 'Insufficient fund in your account'
C1.display() C2=Customer('bikash','silpukhuri',8002,1000.00) C2.display() C2.deposit(1000.00)
try: C2.withdraw(4000.00)
except: print 'Insufficient fund in your account'
C2.display()
Output –
rakesh
guwahati
8001
100000.0
sbi
rakesh
guwahati
8001
40000.0
sbi
bikash
silpukhuri
8002
1000.0
sbi
Insufficient fund in your account
bikash
silpukhuri
8002
2000.0
sbi
Adding static and non-static variables to the class and object from
outside of class.
Example –
class Abc: x=100 def __init__(self): self.y=2000 self.z=3000
Abc.p=4000
print Abc.x
print Abc.p D1=Abc() D1.q=5000
D1.r=6000
print D1.y
print D1.z
print D1.q
print D1.r D2=Abc()
print D2.y
print D2.z
Output –
100
4000
2000
3000
5000
6000
2000
3000
Removing static and non-static variables from class and object
Removing static and non-static variables from class and object
Example –
class Abc: x=100 def __init__(self): self.y=2000 self.z=3000
print Abc.x
del Abc.x D1=Abc()
print D1.y
print D1.z
del D1.y
del D1.z D2=Abc()
print D2.y
print D2.z
Output –
100
2000
3000
2000
3000
Note - If static variable is removed then it is removed for all objects of that
class. But non-static variable is removed only for that particular class.
No comments:
Post a Comment