-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencapsulation.py
54 lines (44 loc) · 1.46 KB
/
encapsulation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 14 21:29:50 2022
@author: shreyastaware
"""
# =============================================================================
# Encapsulation
# Encapsulation is one of the fundamental concepts in object-oriented
# programming (OOP). It describes the idea of wrapping data and the methods
# that work on data within one unit. This puts restrictions on accessing
# variables and methods directly and can prevent the accidental modification
# of data. To prevent accidental change, an object’s variable can only be
# changed by an object’s method. Those types of variables are known as
# private variables.
#
# A class is an example of encapsulation as it encapsulates all the data that
# is member functions, variables, etc.
#
# =============================================================================
# Python program to
# demonstrate private members
# Creating a Base class
class Base:
def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"
# Creating a derived class
class Derived(Base):
def __init__(self):
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
# Uncommenting print(obj1.c) will
# raise an AttributeError
# Uncommenting obj2 = Derived() will
# also raise an AtrributeError as
# private member of base class
# is called inside derived class