super Functionisinstance FunctionAre there any questions before I begin?
Let's look at the answers to Quiz 8.
I have posted a solution to homework 9 here.
Let's take a look.
def __init__(self, collection_no, name, length, format):
self.__collection_no = collection_no
self.__name = name
self.__length = length
self.__format = format
for loop using the string method
isalnum
MIN_NAME_LENGTH = 3
class Video:
...
def __check_name(name):
if type(name) is not str:
raise TypeError("Video constructor expects a string argument for name")
char_count = 0
for char in name:
if char.isalnum():
char_count += 1
if char_count < MIN_NAME_LENGTH:
raise ValueError("Name must have at least " + str(MIN_NAME_LENGTH) + \
" characters that are letters or digits")
MIN_LENGTH = 15
MAX_LENGTH = 1000
class Video:
...
def __check_length(length):
if type(length) is not int:
raise TypeError("Video constructor expects a integer argument for length")
if length < MIN_NAME_LENGTH or length > MAX_LENGTH:
raise ValueError("Length must be at least " + str(MIN_LENGTH) +
" and no more than " + str(MAX_LENGTH))
FORMATS = ("DVD", "Blue Ray")
class Video:
...
def __check_format(format):
if type(format) is not str:
raise TypeError("Video constructor expects a string argument for format")
if format not in FORMATS:
raise ValueError("Format must be one of " + str(FORMATS))
# reads the last collection number used from a file,
# increments that number and writes it back to the file
# and returns the incremented number
def __next_collection_no():
try:
file = open(FILENAME, 'r')
collection_no = int(file.readline())
except FileNotFoundError:
collection_no = 1
else:
collection_no += 1
finally:
file = open(FILENAME, 'w')
file.write(str(collection_no))
return collection_no
def __init__(self, name, length, format):
self.__check_name(name)
self.__check_length(length)
self.__check_format(format)
self.__collection_no = self.__next_collection_no()
self.__name = name
self.__length = length
self.__format = format
def get_collection_no(self):
return self.__collection_no
def get_name(self):
return self.__name
def get_length(self):
return self.__length
def get_format(self):
return self.__format
def __str__(self):
return str(self.__collection_no) + ": " + self.__name + ", " + \
str(self.__length) + " minutes, " + self.__format
from video import Video
class SUBCLASS_NAME(SUPERCLASS_NAME):
class Movie(Video):
Video.__init__(...)
def __init__(self, name, length, format, director, studio):
Video.__init__(self, name, length, format)
self.__director = director
self.__studio = studio
self.__actors = set()
>>> from movie import Movie
>>> m1 = Movie("Forbidden Planet", 98, "DVD", "Fred McLeod Wilcox", "MGM")
>>> str(m1)
'1: Forbidden Planet, 98 minutes, DVD'
>>> m1.get_collection_no() 1 >>> m1.get_name() 'Forbidden Planet' >>> m1.get_length() 98 >>> m1.get_format() 'DVD'
def get_director(self):
return self.__director
def get_studio(self):
return self.__studio
def get_actors(self):
return self.__actors
>>> m1.get_director() 'Fred McLeod Wilcox' >>> m1.get_studio() 'MGM' >>> m1.get_actors() []
def add_actor(self, name):
self.__actors.add(name)
>>> m1.add_actor("Walter Pidgeon")
>>> m1.add_actor("Anne Francis")
>>> m1.add_actor("Leslie Nielson")
>>> m1.add_actor("Warren Stevens")
>>> m1.get_actors()
['Walter Pidgeon', 'Anne Francis', 'Leslie Nielson', 'Warren Stevens']
def __str__(self):
return str(self.__collection_no) + ": " + self.__name + ", " + \
str(self.__length) + " minutes, " + self.__format + \
" Directed by " + self.__director + ", " + self.__studio
>>> str(m1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/glenn/workspace-mars/it117/resources_it117/code_it117/example_code_it117/11_chapter_example_code/movie.py", line 26, in __str__
' Directed by ' + self.__director + ', ' + self.__studio
AttributeError: 'Movie' object has no attribute '_Movie__collection_no'
super Functionsuper
super returns something like a variable ...
def __str__(self):
return super().__str__() + " Directed by " + self.__director + ", " + self.__studio
>>> str(m1) '9: Forbidden Planet, 98 minutes, DVD Directed by Fred McLeod Wilcox, MGM'
super connects to the base class object
def __init__(self, course_name, company, disc_number, instructor, length, format):
Video.__init__(self, "XXX", length, format)
self.__course_name = course_name
self.__company = company
self.__disc_number = disc_number
self.__instructor = instructor
self.__lectures = []
COURSE_NAME: Disc DISC_NO
def get_name(self):
return self.__course_name + ': Disc ' + str(self.__disc_number)
>>> i1.get_name() 'Understanding the Universe: Disc 1'
super().__str__()as we did in Movie
COLLECTION_NO: COURSE_NAME: Disc DISC_NO, INSTRUCTOR
def __str__(self):
return str(super().get_collection_no()) + ': ' + self.get_name() + ', ' + self.__instructor
>>> from instructional import Instructional
>>> i1 = Instructional("Understanding the Universe", "Great Courses", 1, "Alex Filippenko", 180, "DVD")
>>> str(i1)
'1: Understanding the Universe: Disc 1, Alex Filippenko'
def add_lecture(self, lecture):
self.__lectures.append(lecture)
def get_name(self):
return str(super().get_collection_no()) + ": " + self.__course_name + ": Disc " + \
str(self.__disc_number)
def get_course_name(self):
return self.__course_name
def get_company(self):
return self.__company
def get_disc_number(self):
return self.__disc_number
def get_instructor(self):
return self.__instructor
def get_lectures(self):
return self.__lectures
>>> i1.add_lecture("A Grand Tour of the Cosmos")
>>> i1.add_lecture("The Rainbow Connection")
>>> i1.add_lecture("Sunrise, Sunset")
>>> i1.add_lecture("Bright Objects in the Night Sky")
>>> i1.add_lecture("Fainter Phenomena in the Night Sky")
>>> i1.add_lecture("Our Sky Through Binoculars and Telescopes")
>>> i1.get_course_name()
'Understanding the Universe'
>>> i1.get_company()
'Great Courses'
>>> i1.get_disc_number()
1
>>> i1.get_instructor()
'Alex Filippenko'
>>> i1.get_lectures()
['A Grand Tour of the Cosmos', 'The Rainbow Connection', 'Sunrise, Sunset', 'Bright Objects in the Night Sky', 'Fainter Phenomena in the Night Sky', 'Our Sky Through Binoculars and Telescopes'
isinstance Functionisinstance built-in function
isinstance(OBJECT_VARIABLE, CLASS_NAME)
isinstance is a boolean function that returns True or False
>>> isinstance(i1, Movie) False >>> isinstance(i1, Instructional) True
isinstance will also return True ...>>> isinstance(i1, Video) True
>>> from movie import Movie
>>> m1 = Movie("Forbidden Planet", 98, "DVD", "Fred McLeod Wilcox", "MGM")
>>> from instructional import Instructional
>>> i1 = Instructional("Understanding the Universe", "Great Courses", 1, "Alex Filippenko", 180, "DVD")
>>> videos = []
>>> videos.append(m1)
>>> videos.append(i1)
>>> for video in videos:
... print(video)
... print(video.get_name())
...
2: Forbidden Planet, 98 minutes, DVD Directed by Fred McLeod Wilcox, MGM
Forbidden Planet
1: Understanding the Universe: Disc 1, Instructor Alex Filippenko
Understanding the Universe: Disc 1
import random
# # Set up the colors
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
class Shape:
def __init__(self, window, max_width, max_height):
self.window = window
self.color = random.choice((RED, GREEN, BLUE))
self.x = random.randrange(1, max_width - 100)
self.y = random.randrange(25, max_height - 100)
def draw(self):
pass
draw method uses Pygame code to render the shape
class Circle(Shape):
def __init__(self, window, max_width, max_height):
super().__init__(window, max_width, max_height)
self.radius = random.randrange(10, 50)
self.x_center= self.x + self.radius
self.y_center = self.y + self.radius
self.rect = pygame.Rect(self.x, self.y, self.radius * 2, self.radius * 2)
def draw(self):
pygame.draw.circle(self.window, self.color, (self.x_center, self.y_center),
self.radius, 0)
class Square(Shape):
def __init__(self, window, max_width, max_height):
super().__init__(window, max_width, max_height)
self.width_height = random.randrange(10, 100)
self.rect = pygame.Rect(self.x, self.y,
self.width_height, self.width_height)
def draw(self):
pygame.draw.rect(self.window, self.color,
(self.x, self.y, self.width_height, self.width_height))
class Triangle(Shape):
def __init__(self, window, max_width, max_height):
super().__init__(window, max_width, max_height)
self.width = random.randrange(10, 100)
self.height = random.randrange(10, 100)
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
def draw(self):
pygame.draw.polygon(self.window, self.color,
((self.x, self.y + self.height),
(self.x, self.y),
(self.x + self.width, self.y)))
shapes_list = []
shape_classes = (Square, Circle, Triangle)
for i in range(0, NUM_SHAPES):
random_class = random.choice(shape_classes)
shape = random_class(window, WINDOW_WIDTH, WINDOW_HEIGHT)
shapes_list.append(shape)
draw method of each Shape object
for shape in shapes_list:
shape.draw()