Encapsulation adalah konsep dasar dalam Object Oriented Programming (OOP). Encapsulation menyebabkan kita bisa melakuan restriksi.
Restriksi itu dilakukan terhadap metode dan variabel tertentu dalam class.
Apa itu "Object-Oriented Programming?":
- OOP tergantung pada konsep classes dan objects
- Classes mendifinisikan attributes dan metode
- objects dikreasi dari classes
- Untuk contoh, ada class yang disebut car. Attributesnya color, brand dan mode. Kemudian myCar adalah nilai unik dari class.
Memahami Private Method
Kita punya car sebagai class, dimana ada main method, yaitu main method: drive() dan private method: _udateSoftware().
class Car:
def __init__(self):
self.__updateSoftware()
def drive(self):
print('driving')
def __updateSoftware(self):
print('updating software')
redcar = Car()
redcar.drive()
Output:
updating software
driving
Memanfaatkan Private Variabel.
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))
redcar = Car()
redcar.drive()
redcar.__maxspeed = 10 # This won't alter the variable as it's private.
redcar.drive()
Output:
driving. maxspeed 200
driving. maxspeed 200
Sekarang kita ingin mengubah private variabel:
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))
def setMaxSpeed(self, speed):
self.__maxspeed = speed
redcar = Car()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()
Output:
driving. maxspeed 200
driving. maxspeed 320
# Posting sebelumnya:
JJJJJJJJJJJJJJJJ
No comments:
Post a Comment