CS1010S Tutorial 9 PDF
CS1010S Tutorial 9 PDF
Object-Oriented Programming
Quick Recap
- OOP is important.
- Guaranteed one question in finals/practical each.
- If you have to code in your career, chances are you’ll run into this
class Person(NamedObject):
def __init__(self, name):
super.__init__(name)
def poke(self):
return f"{self.name} is annoyed"
Quick Recap: Inheritance
- Diamond Inheritance
- Left to right
- D,B,C,A
- As much as possible, avoid
this
Q1
The essential properties of a Thing are as follows :
1. The constructor should take in 1 parameter, the name of the Thing.
>>> stone = Thing ('stone')
>>> stone.owner
None
>>> stone.is_owned()
False
>>> stone.get_owner()
None
Q1
class Thing(object):
def __init__(self, name):
self.name = name
self.owner = None
def get_owner(self):
return self.owner
def is_owned(self):
return self.owner is not None
Q2
>>> stone . get_name ()
'stone '
place : Just like the owner attribute, we need to keep state of the Place object where the Thing is in.
Similarly, this attributes should be initialized to None when the Thing object is created.
None
None
Q2
class Thing(object):
def __init__(self, name):
self.name = name
self.owner = None
self.place = None ##
def get_name(self): ##
return self.name
def get_place(self): ##
return self.place
Q3
Inside hungry_games.py, you will find that get_name() is captured by the class NamedObject while
get_place() is captured by MobileObject.
Come up with statements whose evaluation will reveal all the properties of ice_cream and verify that its
(new) owner is indeed beng.
Q4.2
Is there anything wrong with the last two statements? What’s the moral of the story?
Q4.3
ice_cream = Thing (" ice_cream ")
Is there anything wrong with the last two statements? What’s the moral of the story?
Nothing is wrong.
Q4.4
rum_and_raisin = NamedObject (" ice_cream ")
Are rum_and_raising and ice_cream the same object? Both are named “ice_cream”.
Q4.4
rum_and_raisin = NamedObject (" ice_cream ")
Are rum_and_raising and ice_cream the same object? Both are named “ice_cream”.
No, They are different objects, only with the same name
Q4.5
burger1 = Thing (" burger ")
Are burger1 and burger2 the same object? Would burger1 == burger2 evaluate to True?
Let’s say we want to a way to compare Thing objects, and objects that have the same name and are at the
same location should evaluate to True when we compare them with ==. How would you do it? (i.e. Objects
like burger1 and burger2 should be considered equal when tested with ==.)
Q4.5