encapsulation
This commit is contained in:
60
src/advance/encapsulation.py
Normal file
60
src/advance/encapsulation.py
Normal file
@ -0,0 +1,60 @@
|
||||
class Car:
|
||||
def __init__(self, brand, price):
|
||||
self.brand = brand # Public attribute
|
||||
self._engine = "V8" # Protected
|
||||
self.__price = price # Private
|
||||
|
||||
# Public method
|
||||
def start(self):
|
||||
print(f"{self.brand} started with {self._engine} engine.")
|
||||
|
||||
# Getter for private attribute
|
||||
def get_price(self):
|
||||
return self.__price
|
||||
|
||||
# Setter for private attribute
|
||||
def set_price(self, new_price):
|
||||
if new_price > 0:
|
||||
self.__price = new_price
|
||||
else:
|
||||
print("Invalid price!")
|
||||
|
||||
|
||||
car = Car("BMW", 50000)
|
||||
|
||||
print(car.brand) # Public
|
||||
print(car._engine) # Possible, but not recommended
|
||||
# print(car.__price) # AttributeError
|
||||
|
||||
print(car.get_price()) # calling getter
|
||||
car.set_price(60000)
|
||||
print(car.get_price())
|
||||
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Encapsulation with @ property (Pythonic Way)
|
||||
|
||||
class BankAccount:
|
||||
def __init__(self, balance):
|
||||
self.__balance = balance # Private
|
||||
|
||||
@property
|
||||
def balance(self):
|
||||
return self.__balance
|
||||
|
||||
@balance.setter
|
||||
def balance(self, new_amount):
|
||||
if new_amount > 0:
|
||||
self.__balance = new_amount
|
||||
else:
|
||||
print("Balance cannot be negative.")
|
||||
raise ValueError("Balance cant be negative")
|
||||
|
||||
|
||||
acc = BankAccount(1000)
|
||||
print(acc.balance)
|
||||
|
||||
acc.balance = 2000 # Calls setter
|
||||
print(acc.balance)
|
||||
|
||||
# acc.balance = -500
|
Reference in New Issue
Block a user