Professional Documents
Culture Documents
Oop PL
Oop PL
▪ Semua benda yang ada di dunia nyata dapat dianggap sebagai objek
Contoh: rumah, mobil, sepeda motor, gelas, komputer, meja, dll
Karateristik Objek
OBJEK
Motor Triseda Motor Balap
roda Aspira Michelin
warna Biru Merah
jumlah roda 3 2
rem Tromol Cakram
Behavior
▪ Sintaksis
class ClassName:
<statement-1>
.
.
.
<statement-N>
Contoh Class
class Employee:
empCount = 0 #attribute
e1 = Employee()
print("Attribute empCount = ", e1.empCount)
e1.displayCount()
Keluaran:
Attribute empCount = 0
Employee count = 0
__init__
def parentMethod(self):
print ('Calling parent method')
def getAttr(self):
print ("Parent attribute :", Parent.parentAttr)
Contoh Inheritance Class (lanjutan)
class Child(Parent): # define child class
def __init__(self):
print ("Calling child constructor")
def childMethod(self):
print ('Calling child method')
def flight(self):
print("Most of the birds can fly but some cannot.")
class Sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class Ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
Contoh Polymorphism (lanj)
obj_bird = Bird()
obj_spr = Sparrow()
obj_ost = Ostrich()
obj_bird.intro()
obj_bird.flight()
Keluaran:
obj_spr.intro()
There are many types of birds.
obj_spr.flight()
Most of the birds can fly but some cannot.
There are many types of birds.
obj_ost.intro() Sparrows can fly.
There are many types of birds.
obj_ost.flight() Ostriches cannot fly.
Abstract Class
class Pentagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 5 sides")
Contoh Abstract Class (lanj)
class Hexagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 6 sides")
class Quadrilateral(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 4 sides")
Contoh Abstract Class (lanj)
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
Keluaran:
R.noofsides()
I have 3 sides
K = Hexagon() I have 4 sides
I have 5 sides
K.noofsides() I have 6 sides
Exception Handling
▪ Sintaksis
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Try Block
print(x)
▪ Ketika perintah di atas dijalankan akan menghasilkan error
• NameError: name 'x' is not defined
Basic Shape
Rectangle Circle
Triangle
Contoh
Basic Shape Class → Parent class
class Shape:
def __init__(self, side1, side2):
self.side1 = side1
self.side2 = side2
def get_area(self):
return self.side1 * self.side2
def __str__(self):
return f'The area of this {self.__class__.__name__} is: {self.get_area()}'
Contoh
Rectangle Class → Child class persegiPanjang = Rectangle(4,5)
class Rectangle(Shape): print(persegiPanjang)
pass
output:
The area of this Rectangle is: 20