Introduction to Biostatistical Computing PHC 6937

Objective Oriented Programming

Zhiguang Huo (Caleb)

Monday Oct 31st, 2022

Introduction

Introduction

A toy example

class Person:

    def setName(self, aname):
        self.name = aname
    
    def greet(self):
        print("Hi there, my name is " + self.name)

a = Person()
a.setName("Lucas")
a.greet()
## Hi there, my name is Lucas

OOP vocabulary

multiple objects from the same class

a = Person()
a.setName("Lucas")
a.greet()
## Hi there, my name is Lucas
b = Person()
b.setName("Amy")
b.greet()
## Hi there, my name is Amy
c = Person()
c.setName("Beth")
c.greet()
## Hi there, my name is Beth

Attributes initialization

class Person:
    
    def __init__(self):
        self.name = "John"
    
    def setName(self, aname):
        self.name = aname
    
    def greet(self):
        print("Hi there, my name is " + self.name)

a = Person()
a.setName("Lucas")
a.greet()
## Hi there, my name is Lucas
b = Person()
b.greet()
## Hi there, my name is John

Class methods

In class exercise (1)

pseudocode for the eat method:
    if hungry==True:
        print("Aaah")
        hungry=False
    else:
        print("No thanks")

The Bird class (1)

class Bird:

    def __init__(self):
        self.hungry = True
    
    def eat(self):
        if self.hungry:
            print("Aaah")
            self.hungry = False
        else:
            print("No, thanks")    

aBird = Bird()
aBird.eat()
## Aaah
aBird.eat()
## No, thanks

Attributes initialization with a user’s input

class Person:
    
    def __init__(self, aname):
        self.name = aname
    
    def setName(self, aname):
        self.name = aname
    
    def greet(self):
        print("Hi there, my name is " + self.name)

a = Person("Lucas")
b = Person("Amy")

a.greet()
## Hi there, my name is Lucas
b.greet()
## Hi there, my name is Amy

Default value in the initialization

class Person:
    
    def __init__(self, aname="John"):
        self.name = aname
    
    def setName(self, aname):
        self.name = aname
    
    def greet(self):
        print("Hi there, my name is " + self.name)
    
a = Person("Lucas")
a.greet()
## Hi there, my name is Lucas
b = Person()
b.greet()
## Hi there, my name is John

Class method (what if there is no self)

class Bird0:
    song = 'Squaawk'
    def sing(self):
        print(self.song)
    def sing2():
        print(song)


bird = Bird0()
bird.sing()
#bird.sing2()
## Squaawk

private method

class Secretive:
    def __inaccessible(self):
        print("Bet you can't see me...")
    def accessible(self):
        print("The secret message is:")
        self.__inaccessible()


s = Secretive()
#s.__inaccessible() ## does not work
s.accessible()
## The secret message is:
## Bet you can't see me...

Class attributes

class Person:
    
    def __init__(self, aname):
        self.name = aname
    
    def getName(self):
        return(self.name)
    
a = Person("Lucas")
a.getName()
## 'Lucas'
a.name  ## alternative way to get attribute
## 'Lucas'

private attribute

class Person:
    
    def __init__(self, aname):
        self.__name = aname
    
    def getName(self):
        return(self.__name)
    
a = Person("Lucas")
a.getName()
#a.__name ## does not work
## 'Lucas'

In class exercise (2)

The Bird class (2)

class Bird2:

    def __init__(self, color="yellow", hungry=True):
        self.color = color
        self.hungry = hungry
    
    def getColor(self):
        return(self.color)
    
    def eat(self):
        if self.hungry:
            print("Aaah")
            self.hungry = False
        else:
            print("No, thanks")    
bBird = Bird2("red")
bBird.getColor()
## 'red'
bBird.eat()
## Aaah
bBird.eat()
## No, thanks

extra argument and keywords in the class initialization

class Car:

    def __init__(self, **kw):
        self.make = kw["make"]
        # self.model = kw["model"]
        self.model = kw.get("model")

my_car = Car(make = "Chevo", model = "Malibu")
print(my_car.model)
## Malibu
my_car = Car(make = "Chevo")
print(my_car.model)
## None

a Class with attributes being other class’s objects

class Person:
    
    def __init__(self, aname="John"):
        self.name = aname
    
    def setName(self, aname):
        self.name = aname
    
    def getName(self):
        return(self.name)
    
    def greet(self):
        print("Hi there, my name is " + self.name)

a Group class

class Group:
    
    def __init__(self):
        self.persons = []
    
    def add(self, aperson):
        self.persons.append(aperson)
    
    def getNameAll(self):
        res = [aperson.getName() for aperson in self.persons]
        return(res)
        
agroup = Group()

agroup.add(Person("Amy"))
agroup.add(Person("Beth"))
agroup.add(Person("Carl"))

agroup.getNameAll()
## ['Amy', 'Beth', 'Carl']

Class inheritance

class Child(Parent):
class Person:
    
    def __init__(self):
        self.name = "John"
    
    def setName(self, aname):
        self.name = aname
    
    def greet(self):
        print("Hi there, my name is " + self.name)
class Student(Person):
    pass
astudent = Student()
astudent.greet()
## Hi there, my name is John

Class inheritance

The child class can have additional attributes and methods compared to the parent class

class Filter:
    def __init__(self):
        self.blocked = [0, 1]
    def filter(self, sequence):
        return [x for x in sequence if x not in self.blocked]
f = Filter()
f.filter([1,2,3])
## [2, 3]
class SPAMFilter(Filter):
    def __init__(self):
        self.blocked = ['SPAM']
s = SPAMFilter()
s.filter(["SPAM","bacan"])
## ['bacan']
issubclass(SPAMFilter, Filter)
## True
issubclass(Filter, SPAMFilter)
## False
class SPAMFilter2(Filter):
    pass
s2 = SPAMFilter2()
s2.filter([1, 2, 3])
## [2, 3]
class SPAMFilter3(Filter):
    def __init__(self):
        self.blocked.append('SPAM')
s3 = SPAMFilter3()
s3.filter([1, 2, "SPAM"])

Super method for python class

class Animal(object):
  def __init__(self, animal_type):
    print('Animal Type:', animal_type)
    
class Mammal(Animal):
  def __init__(self):

    # call superclass
    super().__init__('Mammal')
    ## super(Mammal, self).__init__('Mammal') ## alternatively
    print('Mammals give birth directly')
    
dog = Mammal()
## Animal Type: Mammal
## Mammals give birth directly

Super method for python class

class Filter:
    def __init__(self):
        self.blocked = [0, 1]
    def filter(self, sequence):
        return [x for x in sequence if x not in self.blocked]
class SPAMFilter4(Filter):
    def __init__(self):
        super(SPAMFilter4, self).__init__()
        self.blocked.append('SPAM')
s4 = SPAMFilter4()
s4.filter([1, 2, "SPAM"])
## [2]

In class exercise (3)

def sing(self):
    print(self.sound * 3)

SongBird Class

class Bird:
    
    def __init__(self):
        self.hungry = True
    
    def eat(self):
        if self.hungry:
            print("Aaah")
            self.hungry = False
        else:
            print("No, thanks")    

class SongBird(Bird):
    
    def __init__(self):
        super(SongBird, self).__init__() ## need this to initialize the parental class
        self.sound = "tweet"
    
    def sing(self):
        print(self.sound * 3)
aSongBird = SongBird()
aSongBird.hungry
## True
aSongBird.sound
## 'tweet'
aSongBird.sing()
## tweettweettweet
aSongBird.eat()
## Aaah
aSongBird.hungry
## False
aSongBird.eat()
## No, thanks

Multiple inheritance

class Calculator:
    def calculate(self, expression):
        self.value = eval(expression) ## eval is to evaluate some expression in python

class Talker:
    def talk(self):
        print("Hi, my value is", self.value)

class TalkingCalculator(Calculator, Talker):
    pass
a = TalkingCalculator()
a.calculate("1+1")
a.talk()
## Hi, my value is 2

In class exercise (4)

def sing(self):
    print(self.sound * 3)

SongBird Class

class Bird2:

    def __init__(self, color="yellow", hungry=True):
        self.color = color
        self.hungry = hungry
    
    def getColor(self):
        return(self.color)
    
    def eat(self):
        if self.hungry:
            print("Aaah")
            self.hungry = False
        else:
            print("No, thanks")    

## bBird = Bird2("red")
## bBird.getColor()
## bBird.eat()
## bBird.eat()
class SongBird2(Bird2):
    
    def __init__(self, color="yellow", hungry=True, sound="TWEET"):
        super(SongBird2, self).__init__(color=color, hungry=hungry)
        self.sound = sound
    
    def sing(self):
        print(self.sound * 3)
bSongBird = SongBird2(color="red")
bSongBird.sing()
## TWEETTWEETTWEET
print(bSongBird.getColor())
## red
bSongBird.eat()
## Aaah
bSongBird.eat()
## No, thanks

verify inheritance

issubclass(Bird, SongBird)
## False
issubclass(SongBird, Bird)
## True
issubclass(SongBird2, Bird)
## False
issubclass(SongBird2, Bird2)
## True

Exercise (will be part of HW4)

Exercise (will be part of HW4)

Exercise (will be part of HW4)

Exercise (will be part of HW4)

Reference