Wednesday, 25 January 2017

CLASS IN PYTHON

Class is a syntax or structure used to bind or group the related data members along with its related functionalities.
Syntax –
class classname :
          ----
          ----
          ----

Note – Same indentation is called as suit/block/class

Within the class we can represent data by using static variables and non static variables.


Static variables (class variables) – The variables which are declared within the class, outside of all the methods are known as static variables or class variables. The data which is common for every object is recommended to represent by using static variable. For all the static variables of a class, memory will be allocated only once. Static variables of one class we can access within the same class or outside of the class by using class name.

Example –
class x:
    i=1000                                 // static variable
    def m1(self):
        print x.i
x1=x()                                      // object creation
x1.m1()                                    // 1000
print x.i                                  // 1000
 
We can modify the value of a static variable.


Non-static variable – The variables which are declared with self or reference variable are known as non-static variable or instance variable. Non-static variables we can define within the constructors or within the method. The data which is separate for every object is recommended to represent by using non-static variable. For all the non-static variables of a class, memory will be allocated whenever we create object. With respect to every object creation statement separate copy of the memory will be allocated for non-static variable. Non-static variable of one class, we can access within the same class by using ‘self’. Non-static variables of one class we can access outside the class by using reference variable name

Example –
class abc:
    def m1(self):
        self.i=100
        self.j=123.123
    def display(self):
        print self.i
        print self.j
x=abc()
x.m1()
x.display()
x.i=200
x.j=234.234
x.display()
x1=abc()
x1.m1()
x1.i=300
x1.j=345.345x1.display()
x.display()
 
Output –
100
123.123
200
234.234
300
345.345
200
234.234

No comments:

Post a Comment