Programmering grundkurs Föreläsning 11 Jody Foo, jody.foo@liu.se
Föreläsningsöversikt Laboration 6 Abstraktion och OOP Klassdiagram med UML (Unified Modelling Language) Egna klasser som innehåller andra egna klasser Nedbrytning av problem genom fördelning av ansvar, "delegera vidare uppgiften" Olika implementationsmönster inom OOP Interaktiva textgränssnitt Instans som huvudprogram
Laboration 6 OOP: nya mönster uppdelning av problem klasser med olika roller Interaktiva textgränssnitt Del 1: Representation av text Del 2: Att-göra-lista
Exempel många hus i en stad, befolkning
Exempel på aggregering City name : str add_house(house : House) get_population() : int houses 0..* House occupants : list = [] add_occupant(name : str) get_number_of_occupants() : int
Uppdelning av problem. Exempel på aggregering class City(object): def init (self, name): self.houses = [] self.name = name def add_house(self, house): self.houses.append(house) def get_population(self): total_population = 0 for house in self.houses: total_population += house.get_number_of_occupants() return total_population flaxtown = City("Linköping") house1 = House() house1.add_occupant("a") house1.add_occupant("b") flaxtown.add_house(house1) house2 = House() house2.add_occupant("c") flaxtown.add_house(house2) print(flaxtown) def str (self): city_str = "Name of city: {}\npopulation: {}" return city_str.format(self.name, self.get_population()) class House(object): def init (self): self.occupants = [] def add_occupant(self, name): self.occupants.append(name) def get_number_of_occupants(self): return len(self.occupants)
Exempel böcker i en bok-katalog
Exempel: Böcker i en bok-katalog Två egna klasser: Book, BookCatalogue Ett BookCatalogue-objekt kan innehålla flera Book-objekt BookCatalogue books 1 Book title : str = "Untitled"
books1.py # Exempel där BookCatalogue inte ansvarar för något class Book(object): def init (self, title="untitled"): self.title = title def str (self): return "<Book: '{}'>".format(self.title) class BookCatalogue(object): def init (self): self.books = [] def str (self): books_as_strings = [] for book in self.books: books_as_strings.append(str(book)) return "BookCatalogue: {}".format(", ".join(books_as_strings)) if name == " main ": bc = BookCatalogue() new_book = Book("Book 1") bc.books.append(new_book) new_book = Book("Book 2") bc.books.append(new_book) new_book = Book("Book 3") bc.books.append(new_book) print(bc)
books2.py # Exempel där BookCatalogue tar hand om logistik när nya böcker ska läggas till class Book(object): def init (self, title="untitled"): self.title = title def str (self): return "<Book: '{}'>".format(self.title) class BookCatalogue(object): def init (self): self.books = [] def create_and_add_book(self, title): new_book = Book(title) self.books.append(new_book) def str (self): books_as_strings = [] for book in self.books: books_as_strings.append(str(book)) return "BookCatalogue: {}".format(", ".join(books_as_strings)) if name == " main ": bc = BookCatalogue() bc.create_and_add_book("book 1") bc.create_and_add_book("book 2") bc.create_and_add_book("book 3") print(bc)
books3.py # Exempel där BookCatalogue tar hand om att ha koll på bok-id mha instansvariabel class Book(object): def init (self, book_id, title="untitled"): self.book_id = book_id self.title = title def str (self): return "<Book#{}: '{}'>".format(self.book_id, self.title) class BookCatalogue(object): def init (self): self.books = [] self.book_counter = 0 def create_and_add_book(self, title): new_book = Book(self.book_counter, title) self.book_counter += 1 self.books.append(new_book) def str (self): books_as_strings = [] for book in self.books: books_as_strings.append(str(book)) return "BookCatalogue: {}".format(", ".join(books_as_strings)) if name == " main ": bc = BookCatalogue() bc.create_and_add_book("book 1") bc.create_and_add_book("book 2") bc.create_and_add_book("book 3") print(bc)
books4.py (överkurs) # Exempel där Book tar hand om att ha koll på bok-id mha klassvariabel class Book(object): next_book_id = 0 def init (self, title="untitled"): self.book_id = Book.next_book_id Book.next_book_id += 1 self.title = title def str (self): return "<Book#{}: '{}'>".format(self.book_id, self.title) class BookCatalogue(object): def init (self): self.books = [] def create_and_add_book(self, title): self.books.append(book(title)) def str (self): books_as_strings = [] for book in self.books: books_as_strings.append(str(book)) return "BookCatalogue: {}".format(", ".join(books_as_strings)) if name == " main ": bc = BookCatalogue() bc.create_and_add_book("book 1") bc.create_and_add_book("book 2") bc.create_and_add_book("book 3") print(bc)
Exempel på utökning Flera böcker i bok-katalog Flera bok-kataloger i ett bibliotek... flera bibliotek i en biblioteksorganisation osv
Interaktiva text-gränssnitt
Interaktionsloop med villkor och funktionsanrop def new_book(bookcatalogue): print("new_book() körs") def show_books(bookcatalogue): print("show_books() körs") def main(): bookcatalogue = BookCatalogue() user_input = "" while user_input!= "q": user_input = input("vad vill du göra? ").lower() if user_input == "ny": new_book(bookcatalogue) elif user_input == "visa": show_books(bookcatalogue) if name == ' main ': main()
Interaktionsloop med dictionary och funktionsobjekt def new_book(bookcatalogue): print("new_book() körs") def show_books(bookcatalogue): print("show_books() körs") def main(): commands = {} commands["ny"] = new_book commands["visa"] = show_books bookcatalogue = BookCatalogue() user_input = "" while user_input!= "q": user_input = input("vad vill du göra? ").lower() for command, cmd_func in commands.items(): if command == user_input: cmd_func(bookcatalogue) break if name == ' main ': main()
Interaktiv funktion som skapar ny bok def new_book(bookcatalogue): while True: confirmed = "" title = input("ange titel: ") while confirmed not in ["j", "n"]: confirmed = input("du skrev '{}', är det OK? [j/n]: ".format(title)) if confirmed == "j": bookcatalogue.create_and_add_book(title) break else: print("ok, skriv in igen!")
Utbruten bekräftelsefunktion def get_user_confirmation(message, yes, no): user_input = "" while user_input not in [yes, no]: user_input = input("{} [{}/{}]: ".format(message, yes, no)) if user_input == yes: return True else: return False def new_book(bookcatalogue): while True: confirmed = "" title = input("ange boktitel: ") message = "Du skrev '{}', är det OK?".format(title) user_confirmation = get_user_confirmation(message, "j", "n") if user_confirmation: bookcatalogue.create_and_add_book(title) break else: print("ok, skriv in igen!")
Instans som huvudprogram
Skript som vi brukar skriva dem from books4 import * def get_user_confirmation(message, yes, no): user_input = "" while user_input not in [yes, no]: user_input = input("{} [{}/{}]: ".format(message, yes, no)) if user_input == yes: return True else: return False def new_book(bookcatalogue): while True: confirmed = "" title = input("ange boktitel: ") message = "Du skrev '{}', är det OK?".format(title) user_confirmation = get_user_confirmation(message, "j", "n") if user_confirmation: bookcatalogue.create_and_add_book(title) break else: print("ok, skriv in igen!") def main(): commands = {} commands["ny"] = new_book commands["visa"] = show_books bookcatalogue = BookCatalogue() user_input = "" while user_input!= "q": user_input = input("vad vill du göra? ").lower() for command, cmd_func in commands.items(): if command == user_input: cmd_func(bookcatalogue) break if name == ' main ': main() def show_books(bookcatalogue): print(bookcatalogue)
Skript med instans som "program" from books4 import * def get_user_confirmation(message, yes, no): user_input = "" while user_input not in [yes, no]: user_input = input("{} [{}/{}]: ".format(message, yes, no)) if user_input == yes: return True else: return False class BookApp(object): def init (self): self.commands = {} self.commands["ny"] = self.new_book self.commands["visa"] = self.show_books self.bookcatalogue = BookCatalogue() self.main() def show_books(self): print(self.bookcatalogue) def main(self): user_input = "" while user_input!= "q": user_input = input("vad vill du göra? ").lower() for command, cmd_func in self.commands.items(): if command == user_input: cmd_func() break if name == ' main ': BookApp() def new_book(self): while True: confirmed = "" title = input("ange boktitel: ") message = "Du skrev '{}', är det OK?".format(title) user_confirmation = get_user_confirmation(message, "j", "n") if user_confirmation: self.bookcatalogue.create_and_add_book(title) break else: print("ok, skriv in igen!")