(L7)Programming with Python (Intermediate Level)
(L7)Programming with Python (Intermediate Level)
(Intermediate Level)
Lesson-7 Object-oriented programming
1. Sequential code
2. Conditional code (if statements)
3. Repetitive code (loops)
4. Store and reuse (functions)
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)
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):
print(self.name,"constructed") self.party()
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
def flight(self):
obj_bird.flight()
class sparrow(Bird):
def flight(self):
obj_spr.intro()
print("Sparrows can fly.")
obj_spr.flight()
class ostrich(Bird):
Example:
range(10)
range(1,11)
range(1,100,10)
Method Overloading
class Human:
# Create instance
obj = Human()
if b > 0:
else:
square = Shape()
square.area(5)
rectangle = Shape()
rectangle.area(5, 3)
How to implement method overloading in Python?
Python provides three types of access modifiers private, public, and protected.
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.