50 likes | 144 Vues
Avoiding Rewriting Code:. We can use functions as input parameters We can use inheritance. Functions as input parameters:. from cisc106 import * def speak( f,n ): """ f is a function being passed as an input parameter. """ return f(n) def cat(n): str1 = ""
E N D
Avoiding Rewriting Code: We can use functions as input parameters We can use inheritance
Functions as input parameters: from cisc106 import * def speak(f,n): """ f is a function being passed as an input parameter. """ return f(n) def cat(n): str1 = "" for x in range(n): str1 += "meow " return (str1) def dog(n): str1 = "" for x in range(n): str1 += "woof " return (str1) def seal(n): str1 = "" for x in range(n): str1 += "bark " return (str1) assertEqual(speak(cat,3), "meow meowmeow ") assertEqual(speak(dog, 5), "woof woofwoofwoofwoof ") assertEqual(speak(seal,4), "bark barkbarkbark ")
Functions as input parameters: This is a function that takes as input parameters a function (f) and a number (n) and computes the sum of the series as follows: def series(f, n): """ Computes the sum of the series defined by function f for the first 1 through n terms Input: f -- function n -- number returns – the sum of the series (a number) """ t=0 for i in range(n): t += f(i+1) return t def harmonic(n): return 1.0 / n def geometric_onehalf(n): return (1.0 / 2.0) ** (n-1) def alternating_harmonic(n): return (2 * (n % 2) - 1) * harmonic(n) assertEqual(series(harmonic, 1), 1.0) assertEqual(series(harmonic, 10), 2.9289) assertEqual(series(geometric_onehalf, 2), 1.5) assertEqual(series(geometric_onehalf, 100), 2) assertEqual(series(alternating_harmonic, 2), .5)
Inheritance class Cat(Pet): def __init__(self,sound,weight,name): Pet.__init__(self,name,"cat",weight) self.sound = sound def makesound(self): print(self.sound) ########################################## x = Pet("Fluffy","echidna",20) y = Dog("woof",45,"Lassie","puggle") z = Cat("meow",15,"Sweetie Pie") print(x) print(y) print(z) x.addweight(10) y.addweight(50) print(str(x.weight)) print(str(y.weight)) x.makesound() y.makesound() z.makesound() class Pet(object): def __init__(self,name,species,weight): self.name = name self.species = species self.weight = weight def addweight(self, value): self.weight += value def __str__(self): mystr="My name is “+self.name+" and I am a "+self.species return(mystr) def makesound(self): print("I make animal sounds.") class Dog(Pet): def __init__(self,sound,weight,name,breed): Pet.__init__(self,name,"dog",weight) self.sound = sound self.breed = breed def __str__(self): mystr="My name is "+self.name+" and I am a "+self.breed return(mystr) def makesound(self): str1 = self.sound + " " + self.sound print(str1)