Dictionaries and lists are similar to other sequences list and tuples. Go through the concepts lists and refer to the book if you need more details, focus on OOP.
Reading - Dictionaries and Sets¶
(1-2h)
Read through p.568, stopping before the
Programming Exercises.
Concepts:
9.1 dictionary
temperature_by_city = { "İstanbul" : 20, "København": 12, } temperature_by_city["København"]12Is it in the dictionary?
"İstanbul" in temperature_by_cityTrue"München" not in temperature_by_cityTrueAdding
temperature_by_city["Zürich"] = 20 temperature_by_city{'İstanbul': 20, 'København': 12, 'Zürich': 20}Deleting
del temperature_by_city["Zürich"] temperature_by_city{'İstanbul': 20, 'København': 12}Keys can be any immutable value, values can be anything
mix = {20: ["İstanbul", "Zürich"], 12: ["København", "Hamburg"]}Iteration
for city in temperature_by_city: print(city) for city, temperature in temperature_by_city.items(): print(city, temperature)İstanbul København İstanbul 20 København 12clear,get,items,keys,pop,popitem,valuesExample: deck of cards
deck = {"Ace of Spades": 1, ...}Example: name -> birthday
Merging
age_by_person = {"Ata": 42, "Dilek": 25} age_by_person2 = {"Ata": 24, "Su": 33} age_by_person | age_by_person2{'Ata': 24, 'Dilek': 25, 'Su': 33}Comprehension
{person.upper() for person, age in age_by_person.items() if age < 30}{'DILEK'}
9.2 Sets
Create
activity_ideas = set(["tango", "playing music", "programming"]) activity_ideas{'playing music', 'programming', 'tango'}Add
activity_ideas.add("tango") activity_ideas{'playing music', 'programming', 'tango'}Updating
activity_ideas_by_su = set(["salsa", "watching series", "playing music"]) activity_ideas.update(activity_ideas_by_su) activity_ideas{'playing music', 'programming', 'salsa', 'tango', 'watching series'}Removing vs discarding
activity_ideas.remove("salsa") activity_ideas.remove("salsa") activity_ideas--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[13], line 2 1 activity_ideas.remove("salsa") ----> 2 activity_ideas.remove("salsa") 3 activity_ideas KeyError: 'salsa'activity_ideas.discard("watching series") activity_ideas.discard("watching series") activity_ideas{'playing music', 'programming', 'tango'}Iteration,
in,not insame as listUnion
activity_ideas | activity_ideas_by_su{'playing music', 'programming', 'salsa', 'tango', 'watching series'}Difference
activity_ideas_by_su - activity_ideas{'salsa', 'watching series'}Intersection
activity_ideas_by_su & activity_ideas{'playing music'}Symmetric difference
^issubset,issuperset,<=,>=set comprehensions similar to
dict
9.3 Serializing objects
pickle(andjson) can save Python objects as files. This is also called serialization.Example: take a snapshot of an object, exit the program, and continue the program beginning at the last snapshot.
Analogy to pickling 🏺🥒: We pickle food to conserve it for a longer time, then unpickle it before eating.
Reading - Classes and object-oriented programming¶
(2-3h)
Read through p.628, stopping before the
Programming Exercises.
Concepts:
9.1 object-oriented programming (OOP)
Advantage: reusability
Example: Alarm clock
private methods
public
private vs public methods
sound_alarm(): private because we don’t want that the user can make the alarm sound
set_alarm_time(): for the user
9.2 Classes
class is a blueprint
many objects are created from a class; each is also called an instance
Definition
class Dog: def __init__(self, name, age): self.name = name self.age = age def bark(self): print(f"{self.name} says Woof!") def birthday(self): self.age += 1 print(f"Happy birthday, {self.name}! Now {self.age} years old.")Instantiation
rex = Dog("Rex", 3) fido = Dog("Fido", 5)Usage
rex.bark() fido.birthday() print(rex.name)Rex says Woof! Happy birthday, Fido! Now 6 years old. Rexthe book uses
get_*methods. Do not do this. Use data directly, e.g.,rex.name.[1]This is advanced.
varvs_varvs__var: For now, use justvarclass C: def __init__(self): self.var = 0 self._var = 0 self.__var = 0 c = C() c.var0_varhides but still reachable:c._var0__varreally hides:c.__var--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[23], line 1 ----> 1 c.__var AttributeError: 'C' object has no attribute '__var'Storing classes in modules: similar to functions
Example
BankAccount__str__for printing a class object
10.3 Working with instances
Multiple instances
Accessor and mutator methods (a.k.a getter and setters): As I wrote before, avoid them.
class objects can be passed as function arguments like other objects
Pickling your objects: We will use databases to store process data, but pickling can be useful for storing GUI state.
10.4 Techniques for designing classes
class diagram part of Unified Modeling Language.
Our
Dogclass example:Finding the classes in a problem. (What are the nouns in the problem?)
Refining (some nouns have the same meaning, others we don’t need to be concerned about)
Identifying classes responsibilities
If a class has some instances of another class: Object composition#Aggregation
getter and setter (or accessor and mutator) functions are recommended in OOP, but leads to too much code that does nothing. If needed later, they can be added as properties