xxxxxxxxxx
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
xxxxxxxxxx
# convention: _<name> for protected and __<name> for private
class MyClass:
def __init__(self):
# Protected
# No access outside of the class or subclasses
self._this_is_protected = True
# Private
# No access outside of the class
self.__this_is_private = True
# Note:
# Private and protected members can be accessed outside of the class using python name mangling.
xxxxxxxxxx
# encapsulation in python
class Circle:
def __init__(self, radius):
self.__radius = radius # Private attribute
def area(self):
return 3.14 * self.__radius ** 2
# Creating a Circle object
circle = Circle(5)
# Accessing via a public method
print(circle.area()) # Output: 78.5
image.mefiz.com
https://github.com/MominIqbal-1234