ENCAPSULATION:

The process of binding properties and behaviours in a single unit.

or

The process of binding data and methods in a single unit.

       We can access instance variables inside the class using self specifier.We  can access instance variable outside of the class by reference variable.

Ex-1:    class A():

             a=100

             def m1(self):

                 print(self.a)

         b=A()

         b.m1()

         print(b.a)

If we declare instance variable as private then we can access the variable inside the class only. We cannot access from outside the class.

Ex-2:    class A():

           __a=100

           def m1(self):

             print(self, __a)

          b=A()

          b.m1()

         print(b. __a)

Ex-3:    class A():

            def m1(self):

                print(“m1 method”)

            def m2(self):

                 print(“m2 method”)

         b=A()

         b.m1()

         b.m2()

We can call instance method from outside  of the class using reference variable

Ex-4:    class A():

           def m1(self):

             print(“m1 method”)

           def m2(self):

              print(“m2 method”)

           def m3(self):

              print(“m3 method”)

         a=A()

         a.m3()

         a.m1()

 

We  can access private variables outside of the class using get method.

Ex-5:    class A()

           __a=100

           def m1(self):

              print(self.__ a)

           def get m1(self)

               return self.__ a

        a=A()

        print(a.getm1())

Now we are modifying a=100 as a=200 outside of the class and we are accessing outside of the class.

Ex-6:    class A()

           __a=100

           def set m1(self,a)

             self.__ a=a

           def get m1(self):

              return self.__ a

        a=A()

        a.set m1(200)

        print(a.get m1())


 

Related Posts