Object Oriented Programming23
Object Oriented Programming23
class House:
pass i n i t ( s e l f , c o l o r ) :
def
s el f . c ol or = color Class
firstHouse = House()
firstHouse = House("Yellow")
secondHouse = House()
secondHouse = House("White")
thirdHouse = House()
thirdHouse = House("Pink")
Instance
f i r s t H o u s e . c o l o r = "Yellow"
print(firstHouse.color)
secondHouse.color = "White"
print(secondHouse.color)
thirdHouse.color
p “ Pl oi nr )k "
r i n t ( t h i r d H o u s e .=c o
print(firstHouse.color)
p r i n t ( secondHouse.color)
print(thirdHouse.color)
Car
color Classes vs. instances
model
makeYear
fuelType • Each object is an instance of a class.
start() • A green car is an instance of the car class,
stop() and so is an yellow car.
accelerate()
• The green car might be of the same model as
the yellow, or a different one. But the color is
different at least.
@abstractclassmethod @abstractclassmethod
def s t o p C a r ( s e l f ) : def s t o p C a r ( s e l f ) :
pass pass
car = C a r I n t e r f a c e ( ) class Vo l vo ( Ca r I n t e r f a c e ) :
c a r. s t a r t C a r ( ) def s t a r t C a r ( s e l f ) :
print("Brumm brumm")
return
car = Vo l vo ( )
c a r. s t a r t C a r ( )
from abc import ABC, abstractclassmethod Interfaces and abstract classes,
class CarInterface(ABC): cont. (ísl. skil og hugrænir klasar)
@abstractclassmethod
def s t a r t C a r ( s e l f ) :
pass • Each class that implements an interface,
@abstractclassmethod must implement all of it‘s methods.
def s t o p C a r ( s e l f ) :
pass • If a method isn‘t implemented a
class Vo l vo ( Ca r I n t e r f a c e ) : TypeError will be thrown.
def s t a r t C a r ( s e l f ) :
• TypeError: Can't i n s t a n t i a t e abs trac t
print("Brumm brumm") class Volvo wi th abs trac t methods
return stopCar
def s t o p C a r ( s e l f ) : • Python offers the abc (Abstract Base
return
Class) module for using interfaces and
car = Vo l vo ( ) abstract base classes.
c a r. s t a r t C a r ( )
OOP and UML
• UML has several types of diagrams that are used to describe classes and
operations involving classes:
• Class diagrams (ísl. klasarit)– one of the most common diagrams used.