CONSTRUCTOR:
Constructors logics are executed only when object is created.
Ex-1:
class Myclass(): def __init__(self): print(“Hi”) def wish (self): print(“Hello”) c=Myclass() #Hi c.wish() #Hello
- If global variables name and local variables name is same then we represent global variable with global ().
Ex-1:
a=100 b=200 class Myclass() : def wish (self, name): a,b=10,20 print(a+b) print(name) print(globals()[‘a’]+globals()[‘b]) c=Myclass() c.wish(“Purna”) #30 #Purna #300
Ex-2:
class Myclass(): def __init__(self,a,b): self.a=a self.b=b def add(self) print(a+b) c=Myclass(10,20) c.add() C=Myclass(30,40) c1.add()
ADVANTAGES OF CONSTRUCTOR:
To execute some logics before execution of the method, We can write that logics in constructors.
To initialize instance variables.
Ex-1:
class Myclass() : def __init__(self,a,b,c): self.a=a self.b=b self.c=c def add(self): print(9”name={}/n Id={}/n Salary={}”.format(self.a, self.b, self.c) c=Myclass(“Purna”,111, 10000) c.add() c1=Myclass(“Raju”,222,20000) c1.add()
Ex-2:
class Myclass(): @staticmethod def wish(): print(“good morning”) def disp(self): print(“hello”) c=Myclass() c.disp() Myclass.wish()
- Whenever print the reference variable, controller internally calls underscore undersore(__) str method.
- Pointer contains address of another variable.
Ex-1:
class Myclass(); def wish(): print(“hello”) c=Myclass() c.wish() print(c )
Ex-2:
class Myclass(): def __str__(self): return”Purna” c=Myclass() print( c)
Ex-3:
class Myclass(): def __str__(self) print(“hello”) return “Hai” c=Myclass() print( c)
- Write a program to print employee details using reference variable.
class Myclass(): def __init__(self,a,b,c): self.a=a self.b=b self.c=c def __str__(self): return “name={}/n id={}/n Saalary={}” .fomat(self.a,self.b,self.c) c=Myclass(“Purna”,111,40000) print(c) c1=Myclass(“Hari”,222,20000) print(c1)
Ex-1:
class Myclass(): def __del__(self): print(“destroy”) c=Myclass() del c
Ex-2:
class Myclass(): def __del__(self): print(“destroy”) c=Myclass() c1=Myclass() del c del c1
- If one object with multiple references whenever reference count zero then only del method will be executed.
Ex-3:
class Myclass(): def __del__(self): print(“destroy”) c=Myclass() c1=c c2=c del c