DEV Community

Lakshmi Pritha Nadesan
Lakshmi Pritha Nadesan

Posted on

Day 35 - Abstraction, Encapsulation in Python and Database

Abstraction:

It is the concept of hiding the complex implementation details and showing only the essential features or functionalities to the user.

We create an abstract class by inheriting from the ABC class (which stands for Abstract Base Class) and using the @abstractmethod decorator for abstract methods.

from abc import *
class Parent(ABC):
    @abstractmethod
    def study(self):
        pass

class Child(Parent):
    def study(self):
        print("Commerce")

child = Child()
child.study()
Enter fullscreen mode Exit fullscreen mode
Commerce
Enter fullscreen mode Exit fullscreen mode

The Parent class inherits from ABC, which makes it an abstract class.

The study() method in Parent is defined as an abstract method using the @abstractmethod decorator. This means that any subclass must implement this method.

from abc import *
class Parent(ABC):
    @abstractmethod
    def study(self):
        pass

class Child(Parent):
    def study(self):
        print("Commerce")

    @abstractmethod
    def test(self):
        pass

class GrandChild(Child):
    def test(self):
        pass 
child = GrandChild()
child.study()

Enter fullscreen mode Exit fullscreen mode
Commerce
Enter fullscreen mode Exit fullscreen mode

The code you provided will result in an error because of the way the @abstractmethod decorator is used in the Child class.

The GrandChild class implements the test() method, which is required by the abstract method in the Child class. However, the GrandChild class does not need to implement study() because it is already implemented in the Child class.

Encapsulation:

It restricts direct access to some of the object's attributes or methods to prevent accidental modification and to safeguard the internal state.

In Python, encapsulation is achieved using access modifiers to control the visibility and accessibility of class attributes and methods. There are three main types of access modifiers:

Public:Attributes or methods that are accessible from outside the class. By default, all members are public in Python.
Syntax: No special symbol is needed.
Example: self.attribute_name

Protected:Attributes or methods that should be accessible only within the class and its subclasses.
Syntax: Prefix the member name with a single underscore (_).
Example: _attribute_name

Private:Attributes or methods that should not be accessible from outside the class, making it less prone to accidental modification. Private members are only accessible within the class itself.
Syntax: Prefix the member name with two underscores (__).
Example: __attribute_name

class Infosys:
    employees_count = 100000
    _profit = 100
    __project_bid = 50

    def display(self):
        print(self.employees_count, self._profit, self.__project_bid)

inf = Infosys()
inf.display()

Enter fullscreen mode Exit fullscreen mode
100000 100 50
Enter fullscreen mode Exit fullscreen mode

When you call inf.display(), the method display will print:

self.employees_count (accessible directly, so it prints 100000).
self.profit (protected, but still accessible within the class, so it prints 100).
self.
_project_bid (private, so it will cause an error when accessed directly within the method).

class Infosys:
    employees_count = 100000
    _profit = 100
    __project_bid = 50

    def display(self):
        print(self.employees_count, self._profit, self.__project_bid)

inf = Infosys()
print(inf.employees_count)
print(inf._profit)
print(inf.__project_bid)

Enter fullscreen mode Exit fullscreen mode
100000
100
AttributeError: 'Infosys' object has no attribute '__project_bid'

Enter fullscreen mode Exit fullscreen mode

print(inf.employees_count):Since employees_count is a public attribute, it is directly accessible from outside the class.
Output: 100000

print(inf._profit):_profit is a protected attribute. It’s a convention in Python to indicate that this attribute should not be accessed directly outside the class. However, Python doesn't enforce protection, so you can access it directly, but it is not recommended.
Output: 100

print(inf.project_bid):project_bid is a private attribute. Python internally performs name mangling to prevent direct access. It will not be directly accessible from outside the class, and trying to access it like this will result in an AttributeError.

Database:

A database is an organized collection of structured information, or data, that is typically stored electronically in a computer system.

A database is designed to store, retrieve, and manage data efficiently, allowing users and applications to access, update, and manipulate the data in various ways.

Database Management System (DBMS):

A DBMS is software that manages databases. It provides an interface for interacting with the database, such as adding, updating, or querying data.
Examples of popular DBMS include MySQL, PostgreSQL, SQLite, Oracle, Microsoft SQL Server, and MongoDB.

Relational Databases (RDBMS):

These databases store data in tables and use SQL to query the data. Examples include MySQL, PostgreSQL, Oracle.

Tables:

In a relational database, data is organized into tables. A table consists of rows and columns, where each row represents a record and each column represents an attribute of that record.
For example, a table called Employees might have columns like EmployeeID, Name, Department, Salary, etc.

Hierarchical Database Model :

The Hierarchical Database Model is a type of database model in which data is organized in a tree-like structure, where each record has a single parent and possibly many children.

Network Database Model :

The Network Database Model is an extension of the Hierarchical Database Model, designed to overcome some of the limitations of the hierarchical model.

It allows for more complex relationships between records and supports many-to-many relationships.

Postgresql:

PostgreSQL is a powerful, open-source, object-relational database management system (ORDBMS) that is known for its advanced features, extensibility, and standards compliance.

It is widely used for storing and managing data in large-scale applications, web applications, and even for data warehousing.

Datatypes:

Image description

PostgreSQL Installation:

For Linux open the terminal and type the following commands:

sudo apt update
sudo apt install postgresql postgresql-contrib

Enter fullscreen mode Exit fullscreen mode

Check current status of the postgresql service on a Linux based system.

sudo systemctl status postgresql 

Enter fullscreen mode Exit fullscreen mode

Switch to postgres user:

sudo -i -u postgres
Enter fullscreen mode Exit fullscreen mode

To enter the PostgreSQL interactive terminal (psql), type:

psql
Enter fullscreen mode Exit fullscreen mode

You’ll then be inside the psql prompt, where you can run SQL queries:

\l    # List all databases
\c movie  # Connect to a specific database(movie)
Enter fullscreen mode Exit fullscreen mode

Information about the current version of the database system:

select version();
Enter fullscreen mode Exit fullscreen mode
PostgreSQL 16.6 (Ubuntu 16.6-0ubuntu0.24.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 13.2.0-23ubuntu4) 13.2.0, 64-bit
(1 row)

Enter fullscreen mode Exit fullscreen mode

Creating a table named movie with three columns:

create table movie
(movie_name varchar(80), 
release_date date, 
ticket int
);

Enter fullscreen mode Exit fullscreen mode
CREATE TABLE
Enter fullscreen mode Exit fullscreen mode

movie_name VARCHAR(80): The column movie_name is of data type VARCHAR(80), which means it will hold variable-length strings with a maximum length of 80 characters.

release_date DATE: The column release_date is of data type DATE, which means it will hold dates in the format YYYY-MM-DD.

ticket INT: The column ticket is of data type INT, which will store integer values. This could represent the number of tickets or some other numeric value related to tickets.

Insert values into table:

insert into movie values('vidamuyarchi', '2025-02-06',120); 
insert into movie values('thunivu', '2024-02-06',120); 
insert into movie values('goat', '2024-06-26',120);
Enter fullscreen mode Exit fullscreen mode
INSERT 0 1
INSERT 0 1
INSERT 0 1
Enter fullscreen mode Exit fullscreen mode

Another method to insert values into table:

insert into movie(movie_name, ticket) values('leo', 120);

Enter fullscreen mode Exit fullscreen mode
INSERT 0 1
Enter fullscreen mode Exit fullscreen mode

Select all the values from the movie:

select * from movie;
Enter fullscreen mode Exit fullscreen mode
movie_name  | release_date | ticket 
--------------+--------------+--------
 vidamuyarchi | 2025-02-06   |    120
 thunivu      | 2024-02-06   |    120
 goat         | 2024-06-26   |    120
 leo          |              |    120
(4 rows)
Enter fullscreen mode Exit fullscreen mode

Select only the movie name from the movie:

select movie_name from movie;
Enter fullscreen mode Exit fullscreen mode
movie_name  
--------------
 vidamuyarchi
 thunivu
 goat
 leo
(4 rows)

Enter fullscreen mode Exit fullscreen mode

Calculate ticket price for 4 persons:

select ticket*4 from movie;
Enter fullscreen mode Exit fullscreen mode
?column? 
----------
      480
      480
      480
      480
(4 rows)
Enter fullscreen mode Exit fullscreen mode

Describe the Table Structure:

\d movie;
Enter fullscreen mode Exit fullscreen mode

                         Table "public.movie"
    Column    |         Type          | Collation | Nullable | Default 
--------------+-----------------------+-----------+----------+---------
 movie_name   | character varying(80) |           |          | 
 release_date | date                  |           |          | 
 ticket       | integer               |           |          | 


Enter fullscreen mode Exit fullscreen mode

Task:

Employee Table:
empid integer
empname varchar(30)
designation varchar(30)
dept varchar(20)
salary integer

 empid | empname |    designation    |   dept    | salary 
-------+---------+-------------------+-----------+--------
    11 | Lakshmi | Software Engineer | IT        |  50000
    12 | Guru    | Manager           | HR        |  40000
    13 | Pritha  | Manager           | IT        |  70000
    14 | Gokul   | Team lead         | Sales     |  30000
    15 | Raja    | HR                | Marketing |  65000
    16 | Rani    | HR                | sales     |  45000
(6 rows)

Enter fullscreen mode Exit fullscreen mode

Inserting multiple rows using single insert statement:

In PostgreSQL you can insert multiple rows into a table using a single INSERT statement.

This approach is much more efficient than inserting rows one by one, especially when dealing with large datasets.

Syntax for Inserting Multiple Rows:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES
    (value1_row1, value2_row1, value3_row1, ...),
    (value1_row2, value2_row2, value3_row2, ...),
    (value1_row3, value2_row3, value3_row3, ...),
    ...;

Enter fullscreen mode Exit fullscreen mode

Example:


INSERT INTO employee (employee_id, name, designation_id, dept_id, hire_date)
VALUES
    (1, 'John Doe', 1, 1, '2025-01-01'),
    (2, 'Jane Smith', 2, 1, '2024-05-15'),
    (3, 'Alice Brown', 3, 2, '2023-11-10'),
    (4, 'Bob Johnson', 4, 3, '2022-09-20');

Enter fullscreen mode Exit fullscreen mode

The employee_id values (1, 2, 3, 4) are being inserted into the employee_id column.
The name values ('John Doe', 'Jane Smith', etc.) are inserted into the name column.
Similarly, designation_id, dept_id, and hire_date are populated with the corresponding values for each employee.

Top comments (0)