Create Classes at Python

Dear All, Today, I discuss about Class in Python. in Object Oriented Programming (OOP) we must have known some OOP Concepts such as Inheritance, Polymorhism, Overloading, and of course basic concept using Class and Object. At this ocassion, I would to share to make simple Class in Python for Aritmethics such as how to count largenes from the rectangle. Oke, let's practice, please open your Python IDLE and type code bellow :

>>>class Segiempat:
      def __init__(self, p, l):
         self.panjang = p
         self.lebar = l
     def luas(self):
         return self.panjang * self.lebar
     def keliling(self):
         return 2 * (self.panjang + self.lebar) 

Oke, on the  source code above; we create class named Segiempat and we also create some functions ( init, fucntion of luas and keliling which appears the structurer of largeness and circumference of rectangle. Netxt, please type code bellow on your Pythoc programming:
>>>#Contoh Penggunaan #Creating the object
>>>obj.luas()   #call method luas
output of the program is : 48
>>>obj.keliling() #call metdhod keliling
the output of the program is 28
Class with access modifier Private :
In OOP known access modifier such as Private, Public, Protected and Default. please try the code bellow to know much about access modifier private :
>>>class persegipanjang:
    def __init__(self, p=0, l=0):
        self.__panjang = p
        self.__lebar = l
    def setvalue(self, p, l):
        self.__panjang = p
        self.__lebar = l
    def getp(self):
        return self.__panjang
    def get1(self):
        return self.__lebar
    def luas(self):
        return self.__panjang * self.__lebar

Then, we can try to run or simulate the code above.

>>>#contoh penggunaan
>>> obj = Segiempat(8,6) # membuat objek
>>> obj.luas()          # call metode luas
48
>>> obj.keliling()      # call method keliling
28


Super Class and Child Class with keyword Super
Super Class (named Class induk) and Child class (named Class anak). for this example; we can see, the function of keyword Super, please type the code bellow and try to understand it.

# kelas induk
>>> class induk:
    def __init__(self, x):
        self.x = x
    def printx(self):
        print('Nilai x: %d' % self.x)

       
>>> # kelas turunan
>>> class anak(induk):
    def __init__(self, x, y):
        # call induk. __int__()
        super().__init__(x)
        self.y = y
    def printy(self):
        print('Nilai y: %d' % self.y)
    def printxy(self):
        # call induk.printx()
        super().printx()
        # call metode anak.printy()
        self.printy()

Then, we can try to run or simulate the code above.
       
>>> # memanggil objek dari kelas anak
>>> obj = anak(100,200)
>>>
>>> # memanggil metode printxy()
>>> obj.printxy()
Nilai x: 100
Nilai y: 200

Popular posts from this blog

Introduction to Use Case Diagram - Case study: Facebook

Kenapa tidak berkurban?

Sequential Search