Chapter Four1
Chapter Four1
Chapter Four1
Advanced Topics
Object oriented Programming
Object-oriented programming (OOP) is a method of structuring a program by bundling related
properties and behaviors into individual objects.
Object-oriented programming is based on the imperative programming paradigm, which uses
statements to change a program's state. It focuses on describing how a program should operate.
Examples of imperative programming languages are C, C++, Java, Go, Ruby and Python.
OOP uses the concept of objects and classes. A class can be thought of as a 'blueprint' for
objects. These can have their own attributes (characteristics they possess), and methods (actions
they perform).
One important aspect of OOP in Python is to create reusable code using the concept of
inheritance. This concept is also known as DRY (Don't Repeat Yourself).
The object is created using the class name. When we create an object of the class, it is called
instantiation.
Class Attributes
In Class, attributes can be defined into two parts:
All instances of a class share the class variables. However, unlike instance variables, the value of
a class variable is not varied from object to object. Only one copy of the static variable will be
created and shared between all objects of the class.
Accessing properties and assigning values
An instance attribute can be accessed or modified by using the dot notation:
instance_name.attribute_name.
A class variable is accessed or modified using the class name
Example 2:
#accessing class and instance variable
class person:
age=7
def __init__(self,name):
self.name=name
def display(self):
print("this is a class with out __init__()")
print("i am",self.name,"and i am ",person.age, "years")
y = person("hana")
print(y.age)
y.display()
y.name="dawit"
person.age=15
y.display()
Class Methods
Inside a Class, we can define the following three types of methods.
Instance method: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods.
Class method: Used to access or modify the class state. In method implementation, if we
use only class variables, then such type of methods we should declare as a class method.
Static method: It is a general utility method that performs a task in isolation. Inside this
method, we don’t use instance or class variable because this static method doesn’t have
access to the class attributes.
A constructor is a special method used to create and initialize an object of a class. This method is
defined in the class.
The constructor will be executed automatically when the object is created. If we create three
objects, the constructor is called three times and initializes each object.
The main purpose of the constructor is to declare and initialize instance variables. It can take at
least one argument that is self. The __init()__ method is called the constructor in Python. In
other words, the name of the constructor should be __init__(self).
Non-Parametrized Constructor
A constructor without any arguments is called a non-parameterized constructor. This type of
constructor is used to initialize each object with default values.
This constructor doesn’t accept the arguments during object creation. Instead, it initializes every
object with the same set of values.
#class with non-parameterized constructor
class person:
def __init__(self):
self.name="Abebe"
self.age=15
def display(self):
print("this is a class with non parametrized constructor( __init__(self))")
print(f'Name: {self.name} Age:{self.age}')
y = person()
y.display()
Parameterized Constructor
A constructor with defined parameters or arguments is called a parameterized constructor. We
can pass different values to each object at the time of creation using a parameterized constructor.
The first parameter to constructor is self that is a reference to the being constructed, and the rest
of the arguments are provided by the programmer. A parameterized constructor can have any
number of arguments.
#class with non-parameterized constructor
class person:
def __init__(self,nn,a):
self.name=nn
self.age=a
def display(self):
print("this is a class with parametrized constructor( __init__(self,name,age))")
print(f'Name: {self.name} Age:{self.age}')
O1 = person("sara",20)
N="kebede"
A=30
O2=person(N,A)
O1.display()
O2.display()
If we try to create an object from parameterized constructor like the following statement,
Ob=person( ) Error will be displayed
Constructor overloading is a concept of having more than one constructor with a different
parameters list in such a way so that each constructor can perform different tasks.
Python does not support constructor overloading. If we define multiple constructors then, the
interpreter will considers only the last constructor and throws an error if the sequence of the
arguments doesn’t match as per the last constructor.
In Python, the constructor does not return any value. Therefore, while declaring a constructor, we
don’t have anything like return type. Instead, a constructor is implicitly called at the time of
object instantiation. Thus, it has the sole purpose of initializing the instance variables.
Python Destructors to Destroy the Object
Destructor is a special method that is called when an object gets destroyed. On the other hand, a
constructor is used to create and initialize an object of a class.
A destructor is called when an object is deleted or destroyed. Destructor is used to perform
the clean-up activity before destroying the object, such as closing database connections or file
handle.
Python has a garbage collector that handles memory management automatically. For example, it
cleans up the memory when an object goes out of scope.
The destructor is the reverse of the constructor. The constructor is used to initialize objects,
while the destructor is used to delete or destroy the object that releases the resource occupied by
the object.
In Python, destructor is not called manually but completely automatic. destructor gets called in
the following two cases
When an object goes out of scope or
The reference counter of the object reaches 0.
In Python, The special method __del__() is used to define a destructor. For example, when we
execute del object_name destructor gets called automatically and the object gets garbage
collected.
#using destructor to delete object and object property
class person:
def __init__(self,nn,a=20,add="DB"):
self.name=nn
self.age=a
self.address=add
def display(self):
print("this is a class with defult valued constructor( __init__(self,name,age))")
print(f'Name: {self.name} Age:{self.age} Address: {self.address}')
def __del__(self):
print('this is destructor')
print('Object destroyed')
O1 = person("sara",20)
N="kebede"
O2=person(N)
O1.display()
O2.display()
del O1
del O2.address
If we try to use an object O1.display() which destroyed it will return error
Traceback (most recent call last):
File "<string>", line 20, in <module>
NameError: name 'O1' is not defined
Encapsulation
Encapsulation in Python describes the concept of bundling data and methods within a single
unit. A class is an example of encapsulation as it binds all the data members (instance variables)
and methods into a single unit.
Using encapsulation, we can hide an object’s internal representation from the outside. This is
called information hiding.
Encapsulation is a way to can restrict access to methods and variables from outside of class.
Whenever we are working with the class and dealing with sensitive data, providing access to all
variables used within the class is not a good choice.
Encapsulation can be achieved by declaring the data members and methods of a class either as
private or protected. But In Python, we don’t have direct access modifiers like public, private,
and protected. We can achieve this by using single underscore and double underscores.
Access modifiers limit access to the variables and methods of a class. Python provides three
types of access modifiers private, public, and protected.
Advantages of Encapsulation
Security: The main advantage of using encapsulation is the security of the data.
Encapsulation protects an object from unauthorized access. It allows private and protected
access levels to prevent accidental data modification.
Data Hiding: The user would not know what is going on behind the scene. They would
only know that to modify a data member, call the setter method. To read a data member, call
the getter method. What these setter and getter methods are doing is hidden from them.
Simplicity: It simplifies the maintenance of the application by keeping classes separated and
preventing them from tightly coupling with each other.
Aesthetics: Bundling data and methods within a class makes code more readable and
maintainable
In polymorphism, a method can process objects differently depending on the class type or
data type. Let’s see simple examples to understand it better.
For Example,The built-in function len() calculates the length of an object depending upon its
type. If an object is a string, it returns the count of characters, and If an object is a list, it returns
the count of items in a list. The len() method treats an object as per its class type.
Using method overriding polymorphism allows us to defines methods in the child class that
have the same name as the methods in the parent class. This process of re-implementing the
inherited method in the child class is known as Method Overriding.
In polymorphism, Python first checks the object’s class type and executes the appropriate
method when we call the method.
As you can see, due to polymorphism, the Python interpreter recognizes that the pass_get ()
methods are overridden for the Student and Employee object. So, it uses the one defined in the
child class (Student and Employee)
Method Overloading
The process of calling the same method with different parameters is known as method
overloading. Python does not support method overloading. Python considers only the latest
defined method even if you overload the method. Python will raise a TypeError if you overload
the method.
Inheritance in Python
The process of inheriting the properties of the parent class into a child class is called
inheritance. The existing class is called a base class or parent class and the new class is called a
subclass or child class or derived class.
The main purpose of inheritance is the reusability of code because we can use the existing class
to create a new class instead of creating it from scratch.
In inheritance, the child class acquires all the data members, properties, and functions from the
parent class. Also, a child class can also provide its specific implementation to the methods of
the parent class.
Types of Inheritance
In Python, based upon the number of child and parent classes involved, there are five types of
inheritance.
Single Inheritance: In single inheritance, a child class inherits from a single-parent class. Here
is one child class and one parent class.
#Single Inheritance
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Dog(Animal):
def __init__(self):
self.Age=5
D1=Dog()
D1.Name="boby"
D1.color="brown"
D1.display()
print(D1.Age)
Multiple Inheritance: In multiple inheritance, one child class can inherit from multiple parent
classes. So here is one child class and multiple parent classes.
#Multiple Inheritance
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Dog(Animal):
def __init__(self):
self.Age=5
class Cat(Animal):
def __init__(self):
self.s="Meww"
def CSound(self):
print(f'Cat says {self.s}')
D1=Dog()
D1.Name="cute"
D1.color="white"
D1.display()
print(f'Age: {D1.Age}')
C1=Cat()
C1.Name="cute"
C1.color="white"
C1.display()
C1.CSound()
Multilevel inheritance: In multilevel inheritance, a class inherits from a child class or derived
class. Suppose three classes A, B, C. A is the superclass, B is the child class of A, C is the child
class of B. In other words, we can say a chain of classes is called multilevel inheritance.
# Multilevel Inheritance
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Dog(Animal):
def __init__(self):
self.Age=5
class Puppy(Dog):
def __init__(self):
print("I am little dog")
P1=Puppy()
P1.Name="cute"
P1.color="white"
P1.Age=1
P1.display()
print(f'Age: {P1.Age}')
Hierarchical inheritance: In Hierarchical inheritance, more than one child class is derived from
a single parent class. In other words, we can say one parent class and multiple child classes.
# Hierarchical inheritance
class person:
def __init__(self,name,ID):
self.Name=name
self.Id=ID
def Show(self):
print(f"Name:{self.Name}")
print(f"Name:{self.Id}")
class Employee(person):
def pass_get(self):
print(f"{self.Name} go to his/her office")
class Student(person):
def pass_get(self):
print(f"{self.Name}go to Dorm/Class room")
P=person("hana",1234)
E=Employee("mm",12)
S=Student("ss",12)
E.pass_get()
E.Show()
S.pass_get()
S.Show()
In child class, we can refer to parent class by using the super() function. The super function
returns a temporary object of the parent class that allows us to call a parent class method inside a
child class method.
Benefits of using the super() function:
1. We are not required to remember or specify the parent class name to access its methods.
2. We can use the super() function in both single and multiple inheritances.
3. The super() function support code reusability as there is no need to write the entire
function
#super function used inside cat to call display method of Animal
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Cat(Animal):
def __init__(self):
self.s="Meww"
def CSound(self):
super().display()
print(f'Cat says {self.s}')
C1=Cat()
C1.Name="cute"
C1.color="white"
C1.CSound()
GUI (Graphical User Interface)
A graphical user interface (GUI) is a desktop interface that allows you to communicate with
computers. They carry out various activities on desktop computers, laptops, and other mobile
devices. Text-Editors and other graphical user interface applications build, read, download, and
erase various types of files.
We can use any of the following toolkits in Python for GUI programming.
Tkinter: is a standard package used for GUI programming in Python. This is built on top of
the Tk interface.
PyQt: is a Python toolkit binding of the Qt toolkit. Qt is a C++ framework that is used by
Python to implement a cross-platform PyQt toolkit as a plug-in.
wxPython: wxPython is also a cross-platform GUI toolkit. It is a wrapper for the API
wxWidgets.
Tkinter is the first option for a lot of learners and developers because it is quick and convenient
to use. Tkinter is a Python library that can be used to construct basic graphical user interface
(GUI) applications. In Python, it is the most widely used module for GUI applications.
The creation of a blank GUI interface is the first step of the creation of any GUI. This process of
creating a simple GUI in Tkinter requires the following steps:
1. Tkinter, the first step is to install the Tkinter module in the python shell.
To organize our widgets in window we can use one of the following methods:
1. pack(): This method organizes widgets in blocks before positioning the parent widget. It has
side attribute with value top, bottom, left, right and anchor with value n, ne, nw, s, se, sw, e, w,
center
2. grid(): This method organizes widgets in the grid or table form before positioning the parent
widget. It has two attribute which contain integer values row and column
3. place(): This method organizes the widgets by placing them in the position mentioned in the
code. The position is mentioned based on x-y axis
1. Button:
To add a button to the window, we use the Button() method. Its syntax is given below.
btn=Button(win, option=value), win= name of the window and put following option values
activebackground: This parameter sets the background color when the cursor is on the button.
activeforeground: This parameter sets the foreground color when the cursor is on the button
bg: We give the background color of the button to the parameter
command: We give a function to this parameter. This function contains the code to set the
functionality of the button.
font: This parameter sets the font style of the label of the button
image: This parameter sets the background of the button to the image given
width: This sets the width of the button to the given value
height: This sets the height of the button to the given value
#Example 1
import tkinter
con=tkinter.Tk()
def ff():
print("welcome")
#add widget
B=tkinter.Button(con,text="Click",bg="red",command=ff)
B.grid()
con.mainloop()
Canvas:
This lets you draw shapes such as lines, polygons, etc., and other layouts like graphics, text, and
widgets. Its syntax is given below.
can=Canvas(win, option=value)
The parent window is given as the parameter master. In addition, we have parameters like:
a. bd: This parameter sets the border width. The value should be given in pixels
b. bg: We give the background color of the canvas to this parameter
c. cursor: This sets the cursor used when the cursor is on the canvas
d. highlightcolor: This parameter sets the color of the focus highlight
e. width: This sets the width of the canvas to the given value
f. height: This sets the height of the canvas to the given value
#Example 2
import tkinter
con=tkinter.Tk()
con.title("Welcome to tkinter GUI")
con.geometry("150x200")
ca=tkinter.Canvas(con)
p=ca.create_rectangle(100,150,60,80,fill="blue")
ca.grid()
con.mainloop()
CheckButton:
This widget lets the display multiple options for the user to select. The user can select any
number of checkboxes. Its syntax is:
cb=CheckButton(win, option=value)
The parent window is given as the master. There are many other parameters related to the check
button like:
a. activebackground: This parameter sets the background color when the cursor is on the check
button
b. activeforeground: This parameter sets the foreground color when the cursor is on the check
button
c. bg: We give the background color of the check button
d. command: This takes a function that contains the code to set the functionality of the check
button.
e. font: This parameter sets the font style of the label of the button
f. image: This sets the input image on the check button
#Example 3
import tkinter
con=tkinter.Tk()
con.title("Welcome to tkinter GUI")
con.geometry("150x200")
v1=tkinter.IntVar()
v2=tkinter.IntVar()
cb1=tkinter.Checkbutton(con,text="mango",variable=v1,onvalue=1,offvalue=0)
cb2=tkinter.Checkbutton(con,text="Orange",variable=v2,onvalue=1,offvalue=0)
cb1.pack()
cb2.pack()
con.mainloop()
Entry:
This widget allows you to take single-line input from the user. Its syntax is:
ent=Entry(win, option=value)
The parent window is given as the win. Besides, it has many other parameters like:
a. bd: This parameter sets the border width in pixels
b. bg: We can set the background color of the entry using this parameter
c. cursor: This sets the cursor used when the cursor is on the entry
d. command: This takes a function as an argument that gets called.
e. highlightcolor: This parameter sets the color of the focus highlight
f. width: This sets the width of the entry to the given value
g. height: This sets the height of the entry to the given value
Frame:
This widget acts as a container of other widgets. This is used to organize and position the
widgets. Its syntax is:
frame=Frame(win, option=value)
The parent window is given as the ‘win’ parameter. There are other parameters like:
a. bd: This parameter sets the border width in pixels
b. bg: We can set the background color of the frame using this parameter
c. cursor: This sets the cursor used when the cursor is on the frame
d. highlightcolor: This parameter sets the color of the focus highlight
e. width: This sets the width of the frame
f. height: This sets the height of the frame
Label:
lab=Label(win, option=value)
The parent window is given as the win parameter. There are other parameters like:
a. bd: This parameter sets the border width in pixels
b. bg: We can set the background color of the label using this parameter
c. command: This takes a function that contains the code to set the functionality of the label.
d. font: This parameter sets the font style of the text in the label
e. image: This parameter sets the image to display
f. width: This sets the width of the label
g. height: This sets the height of the label
Listbox:
This widget lets us give a list of items to the user to choose from. Its syntax is:
lb=Listbox(win, option=value)
MenuButton:
This lets us add menus to the GUI. We can add a function to the menu button to open the menu
options. Its syntax is:
mb=MenuButton(win, option=value)
A. activebackground: This parameter sets the background color when the cursor is on the menu
button
B. activeforeground: This parameter sets the foreground color when the cursor is on the menu
button
C. bd: This parameter sets the border width in pixels
D. bg: We can set the background color of the menu button using this parameter
E. cursor: This sets the cursor used in the menu button
F. highlightcolor: This parameter sets the color of the focus highlight
G. image: This parameter sets the background image of the menu button
H. width: This sets the width of the menu button
I. height: This sets the height of the menu button
Let us see an example.
Example of the menu button:
from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
win.geometry('200x100')
mb = Menubutton ( win, text = 'Menu')
mb.grid()
mb.menu = Menu ( mb)
mb['menu'] = mb.menu
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
mb.menu.add_checkbutton ( label ='Home', variable = var1 )
mb.menu.add_checkbutton ( label = 'Profile', variable = var2 )
mb.menu.add_checkbutton ( label = 'Sign Out', variable = var3 )
mb.pack()
win.mainloop() #running the loop that works as a trigger
Menu:
This widget allows us to create all kinds of menus in the application. Its syntax is:
mn=Menu(win, option=value)
The parent window is given as the ‘win’ parameter. In addition, we can set other parameters like:
A. activebackground: This parameter sets the background color when the cursor is on the menu
B. activeforeground: This parameter sets the foreground color when the cursor is on the menu
C. bg: We can set the background color of the menu using this parameter
D. command: This takes a function that contains the code to set the functionality of the menu
E. font: This parameter sets the font style of the text of items in the menu
F. image: This parameter sets the background image of the menu
G. title: This sets the title of the menu
Message: This widget is similar to a label. Here we can display multiline and non-editable text.
Its syntax is:
msg=Message(master, option=value)
The parent window is given as the ‘master’ parameter. The other parameters that let us set other
features are:
A. bd: This sets the border around the message widget
B. bg: We can set the background color of the message using this parameter
C. font: This parameter sets the font style in the message
D. image: This parameter sets the background image of the message widget
E. width: This sets the width of the message
F. height: This sets the height of the message
Radiobutton:
This widget lets us give multiple options to the user and he/she can choose one of the options. Its
syntax is:
rb=Radiobutton(win, option=value)
A. activebackground: This parameter sets the background color when the cursor is on the radio
button
B. activeforeground: This parameter sets the foreground color when the cursor is on the radio
button
C. bg: We can set the background color of the radio button using this parameter
D. command: This takes a function that contains the code to set the functionality of the radio
button.
E. font: This parameter sets the font style if the items in the radio button
F. image: This parameter sets the background image of the radio button widget
G. width: This sets the width of the radio button
H. height: This sets the height of the radio button
Scale: This provides a slider that allows the user to slide any value. Its syntax is:
sc=Scale(win, option=value)
A. activebackground: This parameter sets the background color when the cursor is on the scale
B. bg: We can set the background color of the scale using this parameter
C. cursor: This sets the cursor used in the scale
D. from_: This sets the value of one end of the scale
E. image: This parameter sets the background image of the scale
F. orient: Set the orientation of the widget to either HORIZONTAL or VERTICAL. By default,
it is vertical.
G. to: It sets the value of the other end of the scale.
H. width: This sets the width of the scale
import tkinter
win=tkinter.Tk() #creating the main window and storing the window object in 'win'
sc1= tkinter.Scale(win, from_=0, to=15)
sc1.pack()
sc2 = tkinter.Scale(win, from_=10, to=100, orient='horizontal')
sc2.pack()
win.mainloop() #running the loop that works as a trigger
Scrollbar:
This widget gives the scrolling feature to the other widgets like lists. Its syntax is:
sb=Scrollbar(win, option=value)
A. activebackground: This parameter sets the background color when the cursor is on the
scrollbar
B. bd: This parameter sets the border around the scrollbar
C. bg: We can set the background color of the scrollbar
D. cursor: This sets the cursor used when the cursor is on the scrollbar
E. width: This sets the width of the scrollbar
Text: This is a widget that can be used to display multiline text. Its syntax is:
txt=Text(win, option=value)
The parent window is given as the ‘win’ parameter. The other parameters are:
TopLevel:
This widget provides a separate container window. This does not need a parent window. Its
syntax is:
tl=TopLevel(win, option=value)
The parent window is given as the ‘win’ parameter. The other parameters that let us set other
features are:
A. bd: This parameter sets the border around the top level
B. bg: We can set the background color of the top level
C. cursor: This sets the cursor used when the cursor is on the top level
D. height: This sets the height of the widget
E. width: This sets the width of the top level
SpinBox:
This is similar to the entry widget. Here, instead of entering random input, the user is bound to
enter any of the fixed numbers. Its syntax is:
sb=SpinBox(win, option=value)
The parent window is given as the ‘win’ parameter. The other parameters that let us set other
features are:
A. activebackground: This parameter sets the background color when the cursor is on the
SpinBox
B. bd: This parameter sets the border around the SpinBox
C. bg: We can set the background color of the SpinBox
D. command: This takes a function that contains the code to set the functionality of the SpinBox
E. cursor: This sets the cursor used when the cursor is on the SpinBox
F. from_: This sets the value of one end of the SpinBox
G. to: It sets the value of the other end of the SpinBox.
H. width: This sets the width of the SpinBox
PannedWindow:
This is a widget that acts as a container of multiple panes oriented horizontally or vertically. Its
syntax is:
pw=PannedWindow(win, option=value)
lf=LabelFrame(win, option=value)
tkMessageBox:
This widget is used to show pop-up messages. Remember we used this widget while discussing
the button widget! The syntax of this widget is:
Example of messagebox:
from tkinter import *
from tkinter import messagebox
win=Tk() #creating the main window and storing the window object in 'win'
win.geometry("200x100")
def greet():
messagebox.showinfo("Greetings", "Hello Pythoneer!")
btn = Button(win, text = "Click Me", command = greet)
btn.pack()
win.mainloop()