0% found this document useful (0 votes)
3 views

(L7)Programming with Python (Intermediate Level)

This document covers intermediate-level Python programming, focusing on object-oriented programming concepts such as classes, objects, constructors, destructors, inheritance, and encapsulation. It provides examples of creating classes like PartyAnimal, Book, BankAccount, and Rectangle, along with methods for managing data and behaviors. Additionally, it discusses access modifiers (public, protected, private) and concepts like method overloading and polymorphism.

Uploaded by

hobohin914
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

(L7)Programming with Python (Intermediate Level)

This document covers intermediate-level Python programming, focusing on object-oriented programming concepts such as classes, objects, constructors, destructors, inheritance, and encapsulation. It provides examples of creating classes like PartyAnimal, Book, BankAccount, and Rectangle, along with methods for managing data and behaviors. Additionally, it discusses access modifiers (public, protected, private) and concepts like method overloading and polymorphism.

Uploaded by

hobohin914
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Programming with Python

(Intermediate Level)
Lesson-7 Object-oriented programming

Coding ညေကျာင်း by Code Champs Coding School


Managing larger programs
Four basic programming patterns which we use to construct programs:

1. Sequential code
2. Conditional code (if statements)
3. Repetitive code (loops)
4. Store and reuse (functions)

We explored simple variables as well as collection data structures like lists,


tuples, and dictionaries.
Python provides us with many built-in objects.
For example
stuff = list()
We can take a look at the capabilities of
stuff.append('python')
an object by looking at the output of
stuff.append('chuck') the dir() function:
stuff.sort()
print (stuff[0])
The first line constructs an object of type list
the second and third lines call the append() method
the fourth line calls the sort() method
and the fifth line retrieves the item at position 0.
An object can contain a number of
Our first Python object functions (which we call methods)
as well as data that is used by those
functions.
We call data items that are part of
the object attributes.
We use the class keyword to define
the data and code that will make up
each of the objects.
The class keyword includes the
name of the class and begins an
indented block of code where we
include the attributes (data) and
methods (code).
Our first Python object
Class (Template) object or instance (an)
PartyAnimal of the class PartyAnimal

class PartyAnimal: an = PartyAnimal()

x = 0 an.party()
an.party()
def party(self) : an.party()
self.x = self.x + 1
print("So far",self.x) PartyAnimal.party(an)

When the party method is called, the first parameter (which we call by convention self) points to the
particular instance of the PartyAnimal object that party is called from.
Object lifecycle As Python constructs our object, it calls
our (__init__) method to give us a
class PartyAnimal: chance to set up some default or initial
x = 0 values for the object.

def __init__(self):
print('I am constructed')
Just at the moment when our an object is
def party(self) : being “destroyed” our destructor code
self.x = self.x + 1 (__del__) is called.
print('So far',self.x)

def __del__(self):
print('I am destructed', self.x)

an = PartyAnimal() It actually “throws our object away” so it


an.party() can reuse the an variable to store the
an.party() value 42.
an = 42
print('an contains',an)
Constructor and Destructor
● The constructor and destructor are optional.
● The constructor is typically used to set up variables.
● The destructor is seldom used.
● The primary purpose of the constructor is to set up some instance variables to
have the proper initial values when the object is created
● In object oriented programming, a constructor in a class is a special block of
statements called when an object is created
● Constructors can have additional parameters.
● These can be used to set up instance variables for the particular instance of
the class (i.e., for the particular object).
Many Instances
So far, we have defined a class, constructed a single object, used that object, and
then thrown the object away.

However, the real power in object-oriented programming happens when we


construct multiple instances of our class.

When we construct multiple objects from our class, we might want to set up
different initial values for each of the objects.

We can pass data to the constructors to give each object a different initial value:
Multiple instances
class PartyAnimal:
● We can create lots of objects -
x = 0
the class is the template for the name = ''
object
def __init__(self, nam):
● We can store each distinct object self.name = nam
in its own variable print(self.name,'constructed')
● We call this having multiple def party(self) :
instances of the same class self.x = self.x + 1
print(self.name,'party count',self.x)
● Each instance has its own copy
of the instance variables s = PartyAnimal('Sally')
j = PartyAnimal('Jim')

s.party()
j.party()
s.party()
Book Class
1. Define a Book class with the following attributes: Title, Author (Full name),
Price.
2. Define a constructor used to initialize the attributes of the method with values
entered by the user.
3. Set the View() method to display information for the current book.
4. Write a program to testing the Book class.
BankAccount Class
1. Create a Python class called BankAccount which represents a bank account,
having as attributes: accountNumber (numeric type), name (name of the
account owner as string type), balance.
2. Create a constructor with parameters: accountNumber, name, balance.
3. Create a Deposit() method which manages the deposit actions.
4. Create a Withdrawal() method which manages withdrawals actions.
5. Create an bankFees() method to apply the bank fees with a percentage of
5% of the balance account.
6. Create a display() method to display account details.
Rectangle Class
1. Write a Rectangle class in Python language, allowing you to build a rectangle
with length and width attributes.
2. Create a Perimeter() method to calculate the perimeter of the rectangle and
a Area() method to calculate the area of the rectangle.
3. Create a method display() that display the length, width, perimeter and area
of an object created using an instantiation on rectangle class.
Playing with dir() and type()
class PartyAnimal:
The dir() command lists capabilities-We
x = 0
can use dir() to find the “capabilities” of
our newly created class. def party(self) :
self.x = self.x + 1
Ignore the ones with underscores - print("So far",self.x)
these are used by Python itself
an = PartyAnimal()
The rest are real operations that the
object can perform print("Type", type(an))
print("Dir ", dir(an))
It is like type() - it tells us something
*about* a variable
Inheritance
When we make a new class - we can reuse an existing class and inherit all the
capabilities of an existing class and then add our own little bit to make our new class
Another form of store and reuse
Write once - reuse many times
The new class (child) has all the capabilities of the old class (parent) - and then some
more
‘Subclasses’ or ‘child class’ are more specialized versions of a parent class, which inherit
attributes and behaviors from their parent classes, and can introduce their own.
class PartyAnimal:

x = 0 class FootballFan(PartyAnimal):

name = "" points = 0

def __init__(self, nam): def touchdown(self):

self.name = nam self.points = self.points + 7

print(self.name,"constructed") self.party()

def party(self) : print(self.name,"points",self.points)

self.x = self.x + 1
s = PartyAnimal("Sally")
print(self.name,"party count",self.x)
j = FootballFan("Jim")

s.party()
FootballFan is a class which extends PartyAnimal.
It has all the capabilities of PartyAnimal and more. j.party()

j.touchdown()
Use the super() Function
class Person:
By using the super() function,
def __init__(self, fname, lname):
you do not have to use the name self.firstname = fname
of the parent element, it will self.lastname = lname
automatically inherit the methods
and properties from its parent. def printname(self):
print(self.firstname, self.lastname)
The child's __init__() function
overrides the inheritance of the inheritance
parent's __init__() function.

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
Method Overriding

If you add a method in the


child class with the same
name as a function in the
parent class, the
inheritance of the parent
method will be overridden.
Polymorphism (Having many forms)
In Python, Polymorphism lets us define methods in the child class that have the
same name as the methods in the parent class.
In inheritance, the child class inherits the methods from the parent class.
However, it is possible to modify a method in a child class that it has inherited from
the parent class.
This is particularly useful in cases where the method inherited from the parent
class doesn’t quite fit the child class.
In such cases, we re-implement the method in the child class. This process of
re-implementing a method in the child class is known as Method Overriding.
class Bird: obj_bird = Bird()
def intro(self):
obj_spr = sparrow()
print("There are many types of birds.")
obj_ost = ostrich()

def flight(self):

print("Most of the birds can fly but some cannot.") obj_bird.intro()

obj_bird.flight()
class sparrow(Bird):

def flight(self):
obj_spr.intro()
print("Sparrows can fly.")
obj_spr.flight()

class ostrich(Bird):

def flight(self): obj_ost.intro()


print("Ostriches cannot fly.")
obj_ost.flight()
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.

Example:

range(10)
range(1,11)
range(1,100,10)
Method Overloading
class Human:

def sayHello(self, name=None):

if name is not None:


print('Hello ' + name)
else:
print('Hello ')

# Create instance
obj = Human()

# Call the method


obj.sayHello()

# Call the method with a parameter


obj.sayHello('Guido')
class Shape: Example:
# function with two default parameters

def area(self, a, b=0):

if b > 0:

print('Area of Rectangle is:', a * b)

else:

print('Area of Square is:', a ** 2)

square = Shape()

square.area(5)

rectangle = Shape()

rectangle.area(5, 3)
How to implement method overloading in Python?

Use arbitrary arguments in a function


class Mathematics: to achieve method overloading.

def add(self, *args):


sum = 0
for a in args: Sometimes the programmer does not know the
sum = sum + a number of arguments to be passed into the function.
print(sum)
In such cases, Python arbitrary arguments are used.
obj = Mathematics()
obj.add(8, 9, 12) We use the asterisk (*) to denote this method before
obj.add(8, 9) the parameter in the function.

This is also called as Python *args.


Encapsulation in Python
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.
Access Modifiers in Python
Access modifiers limit access to the variables and methods of a class.

Python provides three types of access modifiers private, public, and protected.

Public Member: Accessible anywhere from outside class.

Private Member: Accessible within the class

Protected Member: Accessible within the class and its sub-classes


Public Member
Public data members are accessible within and outside of a class. All member
variables of the class are by default public.
Protected members
Protected members (in C++ and JAVA) are those members of the class that
cannot be accessed outside the class but can be accessed from within the class
and its subclasses.
To accomplish this in Python, just follow the convention by prefixing the name of
the member by a single underscore “_”.
Although the protected variable can be accessed out of the class as well as in the
derived class(modified too in derived class), it is customary(convention not a rule)
to not access the protected out the class body.
Private members
Private members are similar to protected members, the difference is that the class
members declared private should neither be accessed outside the class nor by
any base class.

In Python, there is no existence of Private instance variables that cannot be


accessed except inside a class.

However, to define a private member prefix the member name with double
underscore “__”.
Public, Protected and Private Data
Attributes and methods in python OOP are either Public, Protected or Private.
A Public attribute or method is usually written without starting with an underscore
character "_". It can be accessed from outside the class, i.e. the value can be read and
changed.
A Protected attribute or method is created by starting its name with one underscore
character "_". Protected members can be accessed like public members from outside of
class, but they are NOT meant to be so.
A Private attribute or method is created by starting its name with two underscore
characters "__", its value cannot be accessed/changed from outside of the class. The
private attribute or method can only be called within the class itself. It can never be
called from outside the class.

You might also like