Object Orientated Programming Flashcards
Write code to define a ‘Track’ Class which contains the title, artist and musical of the song
It also has a method of display the details for the track
class Track(): def \_\_init\_\_(self, title="",artist="",musical=""): self.title = title self.artist = artist self.musical = musical
def showTrack(self): print(self.title, self.artist, self.musical)
Make an instance of the ‘Track’ Class which has a title, artist and musical instance variables
track1 = Track(“You’ll See”, “Adam Pascal”, 2.2)
How do you access methods?
Dot notation
Write the init subroutine in a Playlist class that contains
- An array of tracks
- A max length
- A next track value
Class Playlist(): def \_\_init\_\_(self,maxLength): self.maxLength = maxLength self.tracks = [""]*maxLength self.nextTrack = 0
Write an add track function on a Playlist class where newTrack is passed in and the instance variables in the class are self.maxLength, self.tracks, self.nextTrack
def addTrack(self,newTrack): if self.nextTrack == self.maxLength: print("Playlist is full") else: self.tracks[self.nextTrack] = newTrack self.nextTrack = self.nextTrack + 1
Write a delete track function on a Playlist where index in passed in and the instance variables in the class are self.maxLength, self.tracks, self.nextTrack
def deleteTrack(self,index): if index > self.maxLength or index < 0: print("Invalid index") else: for item in range(index, self.nextTrack-1): self.tracks[item] = self.tracks[item+1] end for self.nextTrack = self.nextTrack - 1
Write the generic code for Inheritance
class SubClass(SuperClass): def \_\_init\_\_(self, attribute1, attribute2, attribute3): SuperClass.\_\_init\_\_(self,attribute1, attribute2) self.attribute3 = attribute3
Write code to define a generic class with two attributes
class Name: def \_\_init\_\_(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2
Create an instance of this class called Pupil 1 with an age of 17 and a name of Heather class Pupil: def \_\_init\_\_(self, age, name): self.age = age self.name = name
pupil1 = Pupil(17,’Heather’)
What is a class?
Blueprint of an object, definitions for the data format and avaliable procedures for a given type of object
What is an object?
An instance of a class
What is Instantiation?
The creation of an object from a class
What is Inheritance?
Sharing of characteristics between a super class and a newly created subclass
What are the benefits of inheritance?(1)
Saves development time, testing already complete, saves lines of code
Describe Polymorphism (2)
A method in a sub class can be written to overwrite the method inherited by the superclass The method called is the one in the subclass instead of the superclass