Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Understanding_Object_Oriented_Programming_in_Python_Slides

Understanding_Object_Oriented_Programming_in_Python_Slides

Uploaded by

Mahmoud Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Understanding_Object_Oriented_Programming_in_Python_Slides

Understanding_Object_Oriented_Programming_in_Python_Slides

Uploaded by

Mahmoud Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Understanding Object Oriented

Programming in Python
Steven Wingett, Babraham Bioinformatics

version 2020-08
Licence
This presentation is © 2020, Steven Wingett & Simon Andrews.

This presentation is distributed under the creative commons Attribution-Non-Commercial-Share Alike 2.0 licence.
This means that you are free:
• to copy, distribute, display, and perform the work
• to make derivative works

Under the following conditions:


• Attribution. You must give the original author credit.
• Non-Commercial. You may not use this work for commercial purposes.
• Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a licence identical to this one.

Please note that:


• For any reuse or distribution, you must make clear to others the licence terms of this work.
• Any of these conditions can be waived if you get permission from the copyright holder.
• Nothing in this license impairs or restricts the author's moral rights.

Full details of this licence can be found at


http://creativecommons.org/licenses/by-nc-sa/2.0/uk/legalcode
Introduction
• So far dealt with Python as a procedural language – a series of
instructions (like a food recipe)
• Easy to loose track of everything for big projects
• Object-oriented programming (OOP) designed to make it easier to
writing more complex projects
• It is better suited to the human brain
Introduction (2)
Vehicles
• Object are analogous to real-
word objects (e.g. vehicles)
• Objects have properties (e.g.
Engine- Human-
number of wheels, max speed) powered powered
• Related objects are grouped
into classes (i.e. vehicles)
Bikes
• And grouped into sub-classes
(e.g. cars, trucks and bikes)
Cars Trucks
Defining classes
• Let’s define a dog class (this is not a dog, but the concept of a dog)

• (Maybe surprisingly, classes are objects as well!)

class Dog:
pass

• Type Dog() into the interpreter:


<__main__.dog object at 0x0341D7B0>

• __main__ is the name of the module to which the dog class belongs (main is the Python interpreter)

• Next is the name of the class followed by an internal memory address (written in hexadecimal)

• Classes by convention begin with capital letters


Instantiation
• To make an instance of the dog class, simply call the class as you
would a function:
snoopy = Dog()

• This is known as instantiation

• This instance of the dog class is named snoopy. Similar to before,


you may view its memory location:
>>> Dog
<__main__.dog object at 0x0410D7F0>
Instance attributes
• Instances of a class may have methods (such as already seen with
built-in objects) and store information in what is known as fields
• Collectively, methods and fields are known as attributes
• Both of these may be accessed using the dot notation:
snoopy.colour = 'White'
• All other instances of the dog class will not have a colour field; only
snoopy will be changed by this statement
• Although this is a simple and quick way to edit the snoopy instance,
there are better ways to do this
Access methods
• Access method returns field values of an instance
• Use def to define a method (similar to a function)
• self refers to the current instance of a class

class Dog:
def get_colour(self):
return self.colour

>>> snoopy.get_colour()
'White'

• Why not simply use snoopy.colour? Well, with our method above, we can change the
internal class code without causing problems.
Access methods (2)
• Access methods do not simply have to return a value:

Class: dog Code interacting with dog


class Dog: snoopy = Dog()
def get_colour(self):
return self.colour snoopy.mood = "Happy"
print((snoopy.animate()))
def animate(self): snoopy.mood = "Angry"
if self.mood == 'Happy': print((snoopy.animate()))
return('Wag Tail') >>>
elif self.mood == 'Angry': Wag Tail
return('Bite') Bite
else:
return('Bark')
Predicate methods
class Dog:
• Return either a True or False stomach_full_percentage = 20
def is_hungry(self):
• By convention, begin with an if(self.stomach_full_percentage < 30):

is_ prefix return True

(or sometimes has_) else:


return False

snoopy = Dog()
print(snoopy.is_hungry())
Predicate methods (2)
• Important method is the ability to compare and sort instances

• By convention, define an __lt__ method to do this

• This method returns True or False (so is a predicate method)


Predicate methods (3)
Code interacting with dog
snoopy = Dog()
snoopy.age = 9

Class: dog scooby = Dog()


class Dog:
scooby.age = 6
def get_age(self):
return self.age
print(snoopy.__lt__(scooby))

def __lt__(self, other):


>>>
if type(self) != type(other):
False
raise Exception(
'Incompatible argument to __lt__:' +
str(other))
return self.get_age() < other.get_age()
Initialisation methods
• Useful to set (or initialise) variables at time of class Dog:
creation def __init__(self, data):
• Special initialisation method: __init__ self.age = data

• This is the usual way to assign values to all def get_age(self):


fields in the class (even if they are assigned to return self.age
None)

• By convention, the __init__ method snoopy = Dog(10)


should be at the top of the code in a class print(snoopy.get_age())

• In the example, we pass self (first) and data to >>>


the __init__ method
10
String methods
• Methods that define how a class should be displayed class Dog:
def __init__(self, data):

• __str__ returned after calling print self.name = data

def __str__(self):
• __repr__ returned by the interpreter return 'Dog:' + self.name

• In example, human-friendly name returned instead def __repr__(self):


of: return self.name
<__main__.dog object at 0x0405D6B0>
>>> dog1
Snoopy
>>> print(dog1)
Dog:Snoopy
Modification methods
Methods that modify class fields:
Code Output
class Dog: >>>
def __init__(self): Sad
self.mood = "Sad"
Happy

def get_mood(self):
return self.mood

def set_mood(self, data):


self.mood = data

dog1 = Dog()
print(dog1.get_mood())
dog1.set_mood("Happy")
print(dog1.get_mood())
Class attributes
• Up until now we have looked at attributes that work at the level of
each instance of a class
• In contrast, there attributes which operate at the level of the whole
class
• Class fields are declared at the top-level and begin with a capital
letter
• Class methods have the special indicator @classmethod on the line
immediately above
• Let’s see an example
Exercises
• Exercise 1.1 & 1.2
Class attributes (2)
Code Output
class Sheep: >>>
Counter = 0 Class field 1
2
@classmethod
def AddOne(self): Class
method
self.Counter += 1

def __init__(self):
self.AddOne()
self.id = self.Counter

def get_id(self):
return self.id

dolly = Sheep()
flossy = Sheep()
print(dolly.get_id())
print(flossy.get_id())
Static methods
• Methods that can be called directly class Utilities:

from a class, without the need for @staticmethod


creating an instance of that class def miles_to_km(miles):
return(miles * 1.60934)

• Special indicator @staticmethod journey = 10


placed on the line immediately above journey_km = Utilities.miles_to_km(journey)
the definition print(journey_km)

• Useful when we need to make use of >>>

a class’s functionality but that class is 16.0934

not needed at any other point in the


code
Exercises
• Exercise 1.3
Inheritance
• Inheritance central to OOP
• Subclass “inherits” Superclass: Vehicles
properties of parent class
(now referred to as the
superclass) Class: Engine- Human-
• Subclass can be modified to powered powered
have different properties
from parent class i.e.
similar, but different Bikes
• Enables coders to produce
objects with reduced
codebase Subclass: Cars Subclass: Trucks
• Reduces code duplication
• Changes only need to be
made in one place
Inheritance (2)
Class Code “Main body” code Output
class Dog: dog1 = Dog() >>>
def __init__(self): print(dog1.get_mood()) Sad
self.mood = "Sad"

def get_mood(self):
return self.mood

def set_mood(self, data):


self.mood = data
Inheritance (3)
Superclass Code Subclass Code “Main body” code Output
class Dog: class Rottweiler(Dog): rottweiler1 = Rottweiler() >>>
def __init__(self): pass print(rottweiler1.get_mood()) Sad
self.mood = "Sad"

def get_mood(self):
return self.mood

def set_mood(self, data):


self.mood = data
Inheritance and super() (2)
• What was the point of that? The Rottweiler class does exactly the
same as the dog class

• Well, once we have created a subclass, we can build on it. See the
following example
Inheritance and super() (3)
Superclass Subclass
class Rectangle: class Square(Rectangle):
def __init__(self, length, width): def __init__(self, length):
self.length = length super().__init__(length, length)
self.width = width

• In geometry, a square is a special type of rectangle


def area(self):
• Here, a Square is a subclass of Rectangle
return self.length * self.width
• Unlike the rectangle, we only need to define the
square’s length on instantiation
def perimeter(self):
• The keyword super refers to the superclass
return 2 * self.length + 2 * self.width
• When initialising a square, we pass length twice to the
initialisation method of the rectangle class
• We have therefore overridden the __init__
method of rectangle
• We can override any superclass method be redefining
it in the subclass
Exercises
• Exercise 2
Exercises
• Exercise 3, 4 and 5*
How do you get to Carnegie Hall? Practice,
practice, practice.

Happy coding!
The Babraham Bioinformatics Team

You might also like