static variables:
- Any variable which define/declare with in the class and outside the methods, that variables are called static variables or class variables.
- one time memory allocation for static variables.
- the data which is common for multiple objects,that data represents static variables.
- we can access static variables with in the class and out side the class by using class name.
- when ever we call a method, method will be executed.
- how to call the method, by using the object.
class test( ):
"""doc string"""
x=10 -----> static variable
def m1(self): ----> method definition
print("i am in method1")
t1=test( ) ------> object creation, t1 is ref variable
print(t1.x) -----> access static variable
t1.m1( ) ------> calling method
print(test.x) ------> access static variable
10
i am in method1
10
Non- static variables:
- the variables which are declared by using self. are known as non-static variables or instance variables.
- syntax: self .variablename
- the data which is separate for every object is recomonded to the represent using non static variables.
- for all the non-static variables of a class memory will be allocated when ever we create the object.
- with respect to every object creation separate copy of the memory will be allocated for non-static variables of the class.
- non static variables of one class can be accessed in to the all the methods of the same class by using self.
- non static variables of one class can be accessed outside of that class by using reference variable.
- memory allocation for non static variables N no.of times.
class test( ):
""" doc string"""
x=1000 ------> static variable
def m1(self): -----> method definition
self.y=10 -----> non static variable
print(test.x)
print(self.y)
t1=test( )
t1.m1( )
1000
10
Note:
- There is a relation between non-static variables and objects.
- There is a no relation between static variables and objects.
- automatically memory allocated for static variables.
- automatically memory is not allocated for non static variables.
- allocating the memory for non-static variables at the time object creation.
- accessing the non static variables in side the class by using self.variablename and out side the class by using reference variable.
No comments:
Post a Comment