Classes

.pdf

School

Toronto Metropolitan University *

*We aren’t endorsed by this school

Course

109

Subject

Computer Science

Date

Dec 6, 2023

Type

pdf

Pages

15

Uploaded by ramabarham18

Report
################# ## EXAMPLE: everything ################# import import unittest unittest ''' Completing this class rundown should mean that you are pretty well-prepared for the upcoming exam questions (or at least most of them) on classes. Generally, concepts you should be familiar with are: 1. Creating an "__init__" method for your class (Including how to make default variables within your class) 2. Accessing, modifying, and defining variables in the class 3. Creating instance methods within your class 4. How to use helper methods alongside classes This question will get you to do all of the above, and I'll identify the relevant sections so you can practice what you need specifically. I'll also be going over the solution to this during the Review Session on Sunday December 5th at 10 am, and I'll post the solutions on the Discord too! ''' ''' Story: The Teletubbies are vanquished, but in the realm of dreams they still haunt you! Your task is to implement the following classes and helper methods according to the requirements described in each class/method, so as to conquer your nightmares, and obliterate all traces of the Teletubbies! ''' class class Dream Dream : ''' Dreams are pretty good. Usually with apple pies and candies and all that good stuff. Your task is as follows: Construct the "__init__" method for a Dream class, that takes in 2 arguments (plus self), self (which you ALWAYS require in your constructors, even if there is nothing else in them!) a string "title", and an int "length" And sets a list dream_elements to start as the empty list: [] [1] Then, once you have completed your constructor, create an instance method called change_title(a), which changes the title of your dream instance to the string a. [2, 3] Then, create another instance method called add_to_dream(topic), which adds the string topic to the dream_elements list. [2, 3] Finally, create an instance method dreams_to_dust(), which replaces each element of the dream_elements list with the string "dust". [2, 3] ''' def def __init__ ( self , title, length, dream_elements = []): self . title = title self . length = int (length) self . dream_elements = [] def def change_title ( self , a): self . title = a def def add_to_dream ( self , topic): # self.topic = topic self . dream_elements . append(topic) def def dreams_to_dust ( self ): for for i in in range ( len ( self . dream_elements)): self . dream_elements[i] = 'dust'
class class Nightmare Nightmare (Dream): # ============================================================================= # ''' # Nightmares are pretty bad. Usually with Teletubbies and chainsaws and all that bad stuff. # Your task is as follows: # Construct the "__init__" method for a Nightmare class, that takes in 0 arguments (except self of course)! # However, you should create an instance variable "topic" that defaults to the string # "Teletubbies", and an instance variable for an attached Dream that the nightmare is # in, called "attached_dream" (which defaults to None). # [1] # Then, create a method attach_to_dream(d), which attached your nightmare instance # to a dream via setting attached_dream to the argument Dream d. # [2, 3] # Then, create a method has_attached_dream() which returns True if your attached_dream # is not None, and False otherwise. # [2, 3] # Finally, create a method WAKE_ME_UP(), which will set the attached_dream's length to 0, # and call it's dreams_to_dust() method. # [2, 3] # ''' # ============================================================================= def def __init__ ( self ): self . topic = "Teletubbies" self . attached_dream = None def def attach_to_dream ( self , d): self . attached_dream = d def def has_attached_dream ( self ): return return self . attached_dream != None def def WAKE_ME_UP ( self ): if if ( self . has_attached_dream()): self . attached_dream . length = 0 self . attached_dream . dreams_to_dust() def def return_titles (list_of_dreams): to_return_list = [] for for dream in in list_of_dreams: to_return_list . append(dream . title) return return to_return_list def def WAKE_ME_UP_INSIDE (cant_wake_up): for for i in in cant_wake_up: i . WAKE_ME_UP() def def how_long_are_my_dreams (list_of_dreams): summ = 0 for for j in in list_of_dreams: summ += j . length return return summ def def __str__ ( self ): print print (return_titles()) # -------------------------------------------------------------- # The Testing # -------------------------------------------------------------- class class myTests myTests (unittest . TestCase):
def def test1 ( self ): # Testing Dream constructor d = Dream( "my awesome dream" , 5 ) self . assertEqual(d . title, "my awesome dream" ) self . assertEqual(d . length, 5 ) self . assertEqual(d . dream_elements, []) def def test2 ( self ): # Testing nightmare constructor n = Nightmare() self . assertEqual(n . topic, "Teletubbies" ) self . assertEqual(n . attached_dream, None ) def def test3 ( self ): # Testing Dream.change_title() d = Dream( "my awesome dream" , 5 ) d . change_title( "my great dream" ) self . assertEqual(d . title, "my great dream" ) def def test4 ( self ): # Testing Dream.add_to_dream() d = Dream( "my awesome dream" , 5 ) d . change_title( "my great dream" ) d . add_to_dream( "rainbows" ) d . add_to_dream( "butterflies" ) self . assertEqual(d . dream_elements, [ "rainbows" , "butterflies" ]) def def test5 ( self ): # Testing Dream.dreams_to_dust() d = Dream( "my ruined dream" , 5 ) d . add_to_dream( "rainbows" ) d . add_to_dream( "butterflies" ) d . add_to_dream( "horsies" ) d . dreams_to_dust() self . assertEqual(d . dream_elements, [ "dust" , "dust" , "dust" ]) def def test6 ( self ): # Testing Nightmare.attach_to_dream() n = Nightmare() d = Dream( "my awesome dream" , 5 ) n . attach_to_dream(d) self . assertEqual(n . attached_dream, d) def def test7 ( self ): n = Nightmare() d = Dream( "my awesome dream" , 5 ) self . assertEqual(n . has_attached_dream(), False ) n . attach_to_dream(d) self . assertEqual(n . has_attached_dream(), True ) def def test8 ( self ): # Testing Nightmare.WAKE_ME_UP() n = Nightmare() d = Dream( "my awesome dream" , 5 ) d . add_to_dream( "pumpkins" ) n . attach_to_dream(d) n . WAKE_ME_UP() self . assertEqual(d . length, 0 ) self . assertEqual(d . dream_elements, [ "dust" ]) def def test9 ( self ): # Testing return_titles() d1 = Dream( "my awesome dream!" , 5 ) d2 = Dream( "my fantastic dream!!" , 4 ) d3 = Dream( "my superb dream!!!" , 3 ) self . assertEqual(return_titles([d1, d2, d3]), [ "my awesome dream!" , "my fantastic dream!!" , "my superb dream!!!" ]) def def test10 ( self ): # Testing WAKE_ME_UP_INSIDE() d1 = Dream( "my awesome dream!" , 5 ) d1 . add_to_dream( "sprinkles" ) d2 = Dream( "my fantastic dream!!" , 4 ) d2 . add_to_dream( "cake" ) d2 . add_to_dream( "chocolates" ) n1 = Nightmare() n2 = Nightmare() n1 . attach_to_dream(d1) n2 . attach_to_dream(d2) WAKE_ME_UP_INSIDE([n1, n2]) self . assertEqual(d1 . length, 0 ) self . assertEqual(d2 . length, 0 ) self . assertEqual(d1 . dream_elements, [ "dust" ]) self . assertEqual(d2 . dream_elements, [ "dust" , "dust" ]) def def test11 ( self ): # Testing how_long_are_my_dreams()
d1 = Dream( "my awesome dream!" , 5 ) d2 = Dream( "my fantastic dream!!" , 4 ) d3 = Dream( "my superb dream!!!" , 3 ) self . assertEqual(how_long_are_my_dreams([d1, d2, d3]), 12 ) if if __name__ == '__main__' : unittest . main( exit = True ) ################# ## EXAMPLE: inheritance ################# ''' Here is the implementation of a parent class called Animal. As you can see, it has the constructor (that __init__) already implemented, as well as a member method. Implement the __eq__ method for animal such that Python returns True if the name and age of both of the animals being compared are identical. You are to write a child class of Animal called Cat. Add another member variable to the Cat class called fur_colour, eye_colour and is_brushed. is_brushed should be automatically set to False. Add another class function called brushies. This function will set the is_brushed member variable to true and print a cat face to the screen (^._.^) Finally, finish the __eq__ function for cat, such that it also compared the other member variables of self to other. Make two Cat objects in the main and call your member method for Brushies on one. Then, compare them and print the result. ''' class class Animal Animal (): def def __init__ ( self , name, age): self . name = name self . age = age def def __eq__ ( self , other): return return ( self . name == other . name) and and ( self . age == other . age) def def take_for_walk ( self ): print print (f "Your {self.name} has gone for a walk!" ) ''' Put your cat class here. ''' class class Cat Cat (Animal): def def __init__ ( self , name, age, fur_colour, eye_colour, is_brushed): Animal . __init__ ( self , name, age) self . fc = fur_colour self . ec = eye_colour self . ib = is_brushed def def brushies ( self ): if if self . ib == True : print print ( '(^._.^)' ) def def __eq__ ( self , other): return return self . ib == other . ib if if __name__ == "__main__" : c1 = Cat( 'Theo' , 2 , 'black' , 'green' , True ) c2 = Cat( 'Mooshi' , 5 , 'white' , 'black' , False ) c1 . brushies() c2 . brushies() print print (c1 . __eq__ (c2)) #################
## EXAMPLE: simple Coordinate class ################# class class Coordinate Coordinate ( object ): """ A coordinate made up of an x and y value """ def def __init__ ( self , x, y): """ Sets the x and y values """ self . x = x self . y = y def def __str__ ( self ): """ Returns a string representation of self """ return return "<" + str ( self . x) + "," + str ( self . y) + ">" def def distance ( self , other): """ Returns the euclidean distance between two points """ x_diff_sq = ( self . x - other . x) **2 y_diff_sq = ( self . y - other . y) **2 return return (x_diff_sq + y_diff_sq) **0.5 c = Coordinate( 3 , 4 ) origin = Coordinate( 0 , 0 ) print print (c . x, origin . x) print print (c . distance(origin)) print print (Coordinate . distance(c, origin)) print print (origin . distance(c)) print print (c) ################# ## EXAMPLE: simple class to represent fractions ## Try adding more built-in operations like multiply, divide ### Try adding a reduce method to reduce the fraction (use gcd) ################# class class Fraction Fraction ( object ): """ A number represented as a fraction """ def def __init__ ( self , num, denom): """ num and denom are integers """ assert assert type (num) == int and and type (denom) == int , "ints not used" self . num = num self . denom = denom def def __str__ ( self ): """ Retunrs a string representation of self """ return return str ( self . num) + "/" + str ( self . denom) def def __add__ ( self , other): """ Returns a new fraction representing the addition """ top = self . num * other . denom + self . denom * other . num bott = self . denom * other . denom return return Fraction(top, bott) def def __sub__ ( self , other): """ Returns a new fraction representing the subtraction """ top = self . num * other . denom - self . denom * other . num bott = self . denom * other . denom return return Fraction(top, bott) def def __float__ ( self ): """ Returns a float value of the fraction """ return return self . num / self . denom def def inverse ( self ): """ Returns a new fraction representing 1/self """ return return Fraction( self . denom, self . num) a = Fraction( 1 , 4 ) b = Fraction( 3 , 4 ) c = a + b # c is a Fraction object print print (c) print print ( float (c)) print print (Fraction . __float__ (c))
print print ( float (b . inverse())) ##c = Fraction(3.14, 2.7) # assertion error ##print a*b # error, did not define how to multiply two Fraction objects ############## ## EXAMPLE: a set of integers as class ############## class class intSet intSet ( object ): """ An intSet is a set of integers The value is represented by a list of ints, self.vals Each int in the set occurs in self.vals exactly once """ def def __init__ ( self ): """ Create an empty set of integers """ self . vals = [] def def insert ( self , e): """ Assumes e is an integer and inserts e into self """ if if not not e in in self . vals: self . vals . append(e) def def member ( self , e): """ Assumes e is an integer Returns True if e is in self, and False otherwise """ return return e in in self . vals def def remove ( self , e): """ Assumes e is an integer and removes e from self Raises ValueError if e is not in self """ try try : self . vals . remove(e) except except : raise raise ValueError ValueError ( str (e) + ' not found' ) def def getMembers ( self ): """Returns a list containing the elements of self. Nothing can be assumed about the order of the elements.""" return return self . vals[:] def def __str__ ( self ): """ Returns a string representation of self """ self . vals . sort() return return '{' + ',' . join([ str (e) for for e in in self . vals]) + '}' # for e in self.vals: # result = result + str(e) + ',' # return '{' + result[:-1] + '}' # -1 omits trailing comma # Instantiation is used to create instances of the class. # For exampl, the following statement creates a new object of type IntSet. # s is called an instance of IntSet. s = intSet() print print (s) s . insert( 3 ) s . insert( 4 ) s . insert( 3 ) print print (s) # Attribute references: use dot notation to access attributes associated with the class. # For example, s.member refers to the method member associated with the instance s of type IntSet s . member( 3 ) s . member( 5 ) s . insert( 6 ) print print (s) #s.remove(5) # leads to an error print print (s)
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help