Instance Variables:
Instance variable are those variables which depends upon the creation of the object.
We can create instance variable by using any of the way you like.
- Using __init__() method
- Using a function defined in the class
- Outside the class
Script: Write an script to demonstrate the creation of instance variables using all three ways above.
class Test:
def __init__(self):
self.a=50
print("Instance Variable a is created using init function ")
def createinstncvar(self):
self.b=10
print("Instance Variable b is created using instance function")
t1=Test()
t1.createinstncvar()
t1.c=30
print("Instance variable c is created outside the class")
print("a=",t1.a," b=",t1.b," c=",t1.c)
Output:
Instance Variable a is created using init function
Instance Variable b is created using instance function
Instance variable c is created outside the class
a= 50 b= 10 c= 30
Instance Variable a is created using init function
Instance Variable b is created using instance function
Instance variable c is created outside the class
a= 50 b= 10 c= 30
**Here self contains current object reference.
Creation of instance variable using __init__() function is more popular and widely used way.
Static Variables:
If you have the background of Java language then for static variables there is static keyword present to create them.
Static variables are not object specific, these are class oriented.
They can be shared by any number of objects of that class in which static variable is defined.
Static variables can be created using
- __init__() method
- instance method
- static method
Script:Write an script which shows the creation of static variables using above three ways.
class Demo:
a=10
def __init__(self):
Demo.b=20
def fun1(self):
Demo.c=30
@staticmethod # This notation is optional but advisable
def fun2():
Demo.d=40
print("Static variable a=",Demo.a," is created in the body of the class")
d1=Demo()
print("Static variable b=",Demo.b," is created using __init__() function")
d1.fun1()
print("Static variable c=",Demo.c," is created using instance function")
Demo.fun2()
print("Static variable d=",Demo.d," is created using static function")
Output:
Static variable a= 10 is created in the body of the class
Static variable b= 20 is created using __init__() function
Static variable c= 30 is created using instance function
Static variable d= 40 is created using static function
Be First to Post Comment !
Post a Comment