#Example of __init__(), __del__(),  class variable, object variable and their uses
class Bbh:
    n=10 # this is class variable
    def __init__(self,x):
        Bbh.n+=20   # 1st use of class variable it will work for every object
        self.n+=10  #2nd use of class variable it will work only once
        self.x=x   # x is the object variable
        print("the value of object variable=",x)
        print("the value of class variable=",self.n)
    def __del__(self):
        Bbh.n=0
        print("Object variable = ",self.x," Class variable= ",self.n) 
        # the above statement print the each of value of object variable 
        # and value of last modified class variable 
# the __init__() like constructor in C++ will be executed automatically
obj1=Bbh(5)
obj2=Bbh(15)
obj3=Bbh(25)
# del is use to free the memory and to execute the method __del__(). It is same as destructor in C++
# but in C++ it executed automatically.
del obj1
del obj2
del obj3
Output:
the value of object variable= 5
the value of class variable= 40
the value of object variable= 15
the value of class variable= 60
the value of object variable= 25
the value of class variable= 80
Object variable =  5  Class variable=  40
Object variable =  15  Class variable=  60
Object variable =  25  Class variable=  80
 
Comments
Post a Comment