Unit 3
Unit 3
Syntax
class ClassName:
#statement_suite
# This is the constructor method that is called when creating a new Person object
# It takes two parameters, name and age, and initializes them as attributes of the object
self.name = name
self.age = age
def greet(self):
A Data Model is a data abstraction model that organizes different elements of data and
standardizes the way they relate to one another and to the properties of real-world entities.
In simple words, Data Modelling in Python is the general process by which this programming
language organizes everything internally and it treats and processes data.
The Data Model is the building block of Python. Internally Data Model has its design and code
blocks for its implementation. It is composed of entities, and entities are none but the
objects.
Each entity has its own attributes (properties) and methods(actions) or behavior associated
with it. Each object has three attributes: an identity, a type, and a value.
Importance of Data Modeling in Python
• Improved Performance
Well-designed data models enhance query performance and reduce data redundancy,
resulting in faster and more efficient data processing.
• Data Integrity
Data modeling defines relationships and constraints, ensuring data consistency and
preventing data corruption.
• Scalability
With a robust data model, it becomes easier to accommodate changing business needs
and effectively scale applications to handle larger datasets.
Types of Data Modeling in Python
Conceptual Data Modeling
These data modeling examples will clarify how data models and the process of data modeling
highlights essential data and the way to arrange it.
• ER (Entity-Relationship) Model
• Hierarchical Model
• Network Model
• Relational Model
• Object-Oriented Database Model
• Object-Relational Model
1. ER (Entity-Relationship) Model
This model is based on the notion of real-world entities and relationships among them. It creates an
entity set, relationship set, general attributes, and constraints.
Here, an entity is a real-world object; for instance, an employee is an entity in an employee database.
An attribute is a property with value, and entity sets share attributes of identical value. Finally, there is
the relationship between entities.
2. Hierarchical Model
This data model arranges the data in the form of a tree with one root, to which other data is connected.
The hierarchy begins with the root and extends like a tree. This model effectively explains several real-
time relationships with a single one-to-many relationship between two different kinds of data.
For example, one supermarket can have different departments and many aisles. Thus, the ‘root’ node
supermarket will have two ‘child’ nodes of (1) Pantry, (2) Packaged Food.
3. Network Model
This database model enables many-to-many relationships among the connected nodes.
The data is arranged in a graph-like structure, and here ‘child’ nodes can have multiple
‘parent’ nodes. The parent nodes are known as owners, and the child nodes are called
members.
4. Relational Model
This popular data model example arranges the data into tables. The tables have columns
and rows, each cataloging an attribute present in the entity. It makes relationships
between data points easy to identify.
For example, e-commerce websites can process purchases and track inventory using the
relational model.
5. Object-Oriented Database Model
6. Object-Relational Model
The basic Python data structures in Python include list, set, tuples,
and dictionary. Each of the data structures is unique in its own
way. Data structures are “containers” that organize and group data
according to type.
• List
• sets
• Dictionary
• Tuple
List
• Lists are used to store data of different data types in a sequential manner.
• There are addresses assigned to every element of the list, which is called
as Index.
• The index value starts from 0 and goes on until the last element called the
positive index.
• There is also negative indexing which starts from -1 enabling you to access
elements from the last to first.
List – [] Square brackets
List
list = [‘ram',‘Ashif',‘tamil',‘krishna']
Print numbers using list -Example
list = [2,4,6,8,10]
for i in list:
print(i)
Output:
2
4
6
8
10
Example2:
List=[5,10,15,20,25]
for i in list:
print(i)
List=[“Ram”,”tamil”,”vijay”,”Ashif”]
for i in list:
print(i)
for using list – Example3
list = [‘ram',‘Ashif',‘tamil',‘krishna']
for i in range(len(list)):
print(list[i])
Output:
ram
zhair
tamil
krishna
Example4:
s = []
for i in range(10):
s.append(i * i)
print s
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List slicing in Python-Example
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
Built-in List Functions & Methods
• Python list method cmp() compares elements of two lists.
Syntax:
cmp(list1, list2)
program
list1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
Output:
-1
1
-1
sets
• A set is an unordered collection of items.
• Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.
• It will not maintains sequence
• Set object does not support indexing
• Sets in Python can be defined as mutable dynamic collections of immutable unique
elements.
Set operations:
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
print(A | B)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
Intersection of sets
• # initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
print(A & B)
Output:
{4, 5}
# Difference of two sets # initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A #
print(A - B)
{1, 2, 3}
use difference function on A
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
>>> A.difference(B)
Output:
{1, 2, 3}
B >>> B.difference(A)
Output: {8, 6, 7}
Symmetric difference of two sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
print(A ^ B)
Output: {1, 2, 3, 6, 7, 8}
add()
update()
len()
remove()
pop()
clear()
del
union()
1.Add()
• To add one item to a set use the add() method.
• To add more than one item to a set use the update() method.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
2. update() :
Get the Length of a Set To determine how many items a set has,
use the len() method.
Example:
5.pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
6.Del()
The del keyword will delete the set completely:
Example:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
7.Clear()
The clear() method empties the set
Example:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
8.clear()
Output:
“cherry” “orange” “kiwi”
Note:
The search will start at index 2 (included) and end at index 5 (not
included).
Remember that the first item has index 0.
Change Tuple Values
• Once a tuple is created, you cannot change its values. Tuples are
unchangeable, or immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.
• Convert the tuple into a list to be able to change it:
• Output:
Yes, 'apple' is in the fruits tuple
Tuple Length
•
To determine how many items a tuple has,
use the len() method:
• Print the number of items in the tuple:
3
Add Items
# Accessing elements
print(dimensional grid[0][0]) # Output: 1
print(dimensional grid[1][2]) # Output: 6
EXAMPLE CODE -2
• For more advanced and efficient operations on multi-dimensional arrays,
especially for numerical computations, you might want to use the NumPy library:
import numpy as np
Presentation title 45
2.structuring classes with inheritance and polymorphism
Presentation title 46
Inheritance
• Inheritance is the capability of one class to derive or inherit the properties from
another class. The benefits of inheritance are:
• Inheritance enables us to define a class that takes all the functionality from a parent
class and allows us to add more.
• The new class is called derived (or child) class and the one from which it inherits is
called the base (or parent) class.
• Inheritance allows programmer to create a general or a base class first and then later
extend it to more specialized class. It allows programmer to write better code.
Presentation title 47
• Using inheritance you can use or inherit all the data fields and methods available in your
base class. Later you can add you own methods and data fields, thus inheritance provides
a way to organize code, rather than rewriting it from scratch.
• In object-oriented terminology when class X extend class Y, then Y is called
super/parent/base class and X is called subclass/child/derived class. One point to note
here is that only data fields and method which are not private are accessible by child
classes. Private data fields and methods are accessible only inside the class.
class BaseClass:
Body of base class class
--------------------
--------------------
Class Derivedclass(BaseClass):
Body of derived class
-----------------------
-----------------------
Presentation title 48
Class student:
___________
___________
____________
Class mark(student):
______________
_____________
____________--
Types of inheritance Python
Single Inheritance:
class mark(student):
def read(self):
self.m1=input("enter mark1")
self.m2=input("enter mark2")
def disp(self):
print(self.name)
print(self.no)
print(self.m1)
print(self.m2)
m=mark()
m.get()
m.read()
m.disp()
Multilevel Inheritance :
In multilevel inheritance, features of the base class and the derived class
are further inherited into the new derived class. This is similar to a
relationship representing a child and a grandfather.
Program 2 - Multilevel
class personal:
def get(self):
self.name=input("Enter name: ")
self.reg=input("Enter Regno: ")
class marks(personal):
def read(self):
self.m1=int(input("Enter Mark 1: "))
self.m2=int(input("Enter Mark 2: "))
class total(marks):
def cal(self):
self.tot=self.m1+self.m2
def disp(self):
print(self.name)
print(self.reg)
print(self.m1)
print(self.m2)
print(self.tot)
t= total()
t.get()
t.read()
t.cal()
t.disp()
Multiple Inheritance:
When a class can be derived from more than one base class
this type of inheritance is called multiple inheritances. In
multiple inheritances, all the features of the base classes are
inherited into the derived class.
Program 3 - Multiple
class personal:
def get(self):
self.name=input("Enter name: ")
self.reg=input("Enter Regno: ")
class marks:
def read(self):
self.m1=int(input("Enter Mark 1: "))
self.m2=int(input("Enter Mark 2: "))
class total(personal,marks):
def cal(self):
self.tot=self.m1+self.m2
def disp(self):
print(self.name)
print(self.reg)
print(self.m1)
print(self.m2)
print(self.tot)
t= total()
t.get()
t.read()
t.cal()
t.disp()
Hybrid Inheritance
Inheritance consisting of multiple types of inheritance is called
hybrid inheritance.
Program 4 - Hybrid
class personal:
def get(self):
self.name=input("Enter name: ")
self.reg=input("Enter Regno: ")
class marks(personal):
def read(self):
self.m1=int(input("Enter Mark 1: "))
self.m2=int(input("Enter Mark 2: "))
class average:
def avg(self):
self.a = (self.m1+self.m2)/2
print(self.a)
class total(marks,average):
def cal(self):
self.tot=self.m1+self.m2
def disp(self):
print(self.name)
print(self.reg)
print(self.m1)
print(self.m2)
print(self.tot)
t= total()
t.get()
t.read()
t.cal()
t.disp()
t.avg()
Polymorphism (“MANY SHAPES”)
• Polymorphism is an important feature of class definition in Python that is
utilized when you have commonly named methods across classes or
subclasses. This permits functions to use entities of different types at
different times. So, it provides flexibility and loose coupling so that code
can be extended and easily maintained over time.
def area(self):
pass # To be implemented by subclasses
def display_info(self):
print(f"Color: {self.color}, Area: {self.area()}")
Presentation title 63
EXAMPLE CODE
Subclasses (Circle and Rectangle):
•They inherit from the Shape class using class Circle(Shape): and class Rectangle(Shape):.
•They provide their own implementations of the area method.
# Subclass 1
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
64
EXAMPLE CODE
# Subclass 2
class Rectangle(Shape):
def __init__(self, color, width, height):
super().__init__(color)
self.width = width
self.height = height
def area(self):
return self.width * self.height
Presentation title 65
EXAMPLE CODE
Polymorphic function (print_shape_info):
•It takes a Shape object as a parameter and calls the display_info method.
•This function can work with any subclass of Shape, demonstrating polymorphism.
# Polymorphic function
def print_shape_info(shape):
shape.display_info()
# Example usage
circle = Circle("Red", 5)
rectangle = Rectangle("Blue", 4, 6)
print_shape_info(circle)
print_shape_info(rectangle)
Presentation title 66
3.Graphical use interfaces
• A Graphical User Interface (GUI) is a type of user interface that allows
users to interact with electronic devices through graphical elements such
as icons, buttons, and windows, rather than text-based interfaces. GUIs
are commonly used in software applications to provide a more user-
friendly and visually intuitive experience.
Presentation title 67
Tkinter
Tkinter is the standard GUI (Graphical User Interface) toolkit that comes with Python. It is a built-in library
and is widely used for creating desktop applications with graphical interfaces. Tkinter is based on the Tk
GUI toolkit and provides a set of tools for creating windows, dialogs, buttons, text boxes, and other GUI
elements.
Key points
1. Cross-Platform: Tkinter is cross-platform, meaning that applications developed using Tkinter can run on
various operating systems, including Windows, macOS, and Linux, without modification.
2. Simple and Lightweight: Tkinter is known for its simplicity and ease of use, making it an excellent choice
for beginners in GUI programming. It's lightweight and suitable for small to medium-sized projects.
3. Widgets: Tkinter provides a variety of GUI widgets that can be used to build the user interface of an
application. These include labels, buttons, entry fields, text widgets, canvas, and more.
Presentation title 68
4.Event-Driven Programming: Tkinter follows an event-driven
programming paradigm. User actions, such as clicking a button or
typing in an entry field, trigger events that are handled by callback
functions.
5.Integration with Python: Being part of the Python standard
library, Tkinter integrates seamlessly with Python. It is easy to use
in conjunction with other Python libraries and modules.
6.Open Source: Tkinter is open source and freely available for use
and distribution.
Presentation title 69
Tkinter – EXAMPLE
import tkinter as tk
def on_button_click():
label.config(text="Button Clicked!")
# Create a button
button = tk.Button(root, text="Click me!", command=on_button_click)
button.pack(pady=10)
# Create a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)
Presentation title 72