<class 'str'>
PHOT 110: Introduction to programming
LECTURE 11: Object Oriented Programming: Classes (Ch. 7 & 9)
Michaël Barbier, Spring semester (2023-2024)
An object is an instance of a class
class spaceship:
def __init__(self, pos_0, orient_0, image):
self.position = pos_0
self.orientation = orientation_0
self.image = image
def teleport(self, displacement):
self.position = self.position + displacement
def test_collision(pos, R):
if (pos - self.position)**2 < R ** 2:
return True
return False
Adding attributes per object
Adding attributes per object
Special methods use double underscores in their name:
__init__()
__call__()
__str__()
Operator overloading: Using operators +
, -
, *
between objects
__ne__()
__add__()
Formula can be called like a function:
Using for example “+” between custom class objects
Cargo delivery service: We want to transport goods
deliver()
?Bus transport of persons
Do we need to write code for a whole new class ?
We can derive a class from another class
Make a derived class (subclass)
super()
to access BaseClasssuper().__init__()
to have BaseClass constructor
Lecture 11: Object Oriented Programming: Classes (Ch. 7 & 9)