2.7. Lecture 6: Python 4¶
Before this class you should:
Read Think Python:
Chapter 15: Classes and objects;
Chapter 16: Classes and functions;
Chapter 17: Classes and methods; and
Chapter 18: Inheritance
Before next class you should:
Read Think Complexity, Chapter 2
Read the Wikipedia page about graphs at https://en.wikipedia.org/wiki/Graph_(discrete_mathematics) and answer the following questions:
What is a simple graph? For our discussion today, we will assume that all graphs are simple graphs. This is a common assumption for many graph algorithms – so common it is often unstated.
What is a regular graph? What is a complete graph? Prove that a complete graph is regular.
What is a path? What is a cycle?
What is a forest? What is a tree? Note: a graph is connected if there is a path from every node to every other node.
Note Taker: Arnold Tom-George
Today’s class was an introduction to a new topics called Tuples and Classes.
- Objectives:
Understand how to use tuples
Relate previous knowledge of lists
Using tuples and dictionaries
Understand how to use Classes and Objects
How to define a class
Inheritances
2.8. Tuples¶
Definition: Tuples are immutable sequences of values. Syntax: Comma-separated values, e.g., (1, 2, 3). Single-element tuple: (1,). Conversion: Use tuple(sequence) to convert sequences like strings or lists into tuples.
2.9. Tuples vs Lists in Python¶
Tuples: Immutable; use for fixed data; Use tuples when you need a collection of items that should remain constant throughout the program.
Lists: Mutable; use for data that changes; Use lists when you have a collection of items that are likely to change.
2.10. Characteristics:¶
Immutable: Cannot modify elements after creation.
Supports most list operators like indexing and slicing.
Useful in cases where immutability is required, such as keys in dictionaries.
2.10.1. Zip Function¶
The zip function combines two or more sequences element-wise into a list of tuples. This means it pairs together the first elements of each sequence, then the second elements, and so on.
- Example:
zip('abc', [1, 2, 3])
results in[('a', 1), ('b', 2), ('c', 3)]
Here, ‘a’ is paired with 1, ‘b’ with 2, and ‘c’ with 3.
- Example:
- The length of the resulting list is determined by the shortest input sequence.
Example:
zip('ab', [1, 2, 3])
results in[('a', 1), ('b', 2)]
Notice that since the shortest sequence (‘ab’) has only 2 elements, the output is limited to 2 pairs.
By understanding the element-wise nature of zip, you can effectively combine sequences in a structured and predictable manner.
2.10.2. Dictionaries with Tuples:¶
Use tuples as keys in dictionaries since they are immutable.
Example: directory[(last_name, first_name)] = phone_number.
Methods:
items(): Returns key-value pairs as tuples. Iterate with for key, value in d.items(). Creating Dictionaries:
Use zip: dict(zip(keys, values)).
You can use zip()
to combine two lists into key-value pairs and convert them into a dictionary.
Example:
keys = ["name", "age", "city"]
values = ["Alice", 25, "New York"]
person_dict = dict(zip(keys, values))
print(person_dict)
Output:
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Use args to collect variable numbers of arguments into a tuple.
Example:
def print_all(*args*):
print(args)
print_all(1, 2, 3, "hello", True)
Output:
(1, 2, 3, 'hello', True)
Consider a function that logs error messages with multiple details:
def log_error(*messages):
for message in messages:
print(f"ERROR: {message}")
log_error("File not found", "Permission denied", "Disk full")
Use to unpack a sequence into function arguments.
Example: divmod((7, 3))
.
In the second part of this class we talked about Classes and Objects.
2.11. Classes and Objects¶
Classes serve as blueprints for creating objects, defining both their attributes (data) and methods (behaviors). Python’s implementation of classes is straightforward yet powerful:
Class Definition:
Uses the
class
keyword followed by the class nameObject Creation: Objects are instances of classes, created by calling the class like a function
Attributes: Store object-specific data, accessed using dot notation
Methods: Functions defined within classes that operate on object data
2.11.1. Class Implementation Examples¶
Card Game System
The card game implementation demonstrates practical OOP usage:
Card Class:
Represents individual playing cards
Uses attributes for suit and rank
Implements comparison methods
Utilizes class attributes for suit and rank names
Deck Class:
Manages a collection of cards
Provides methods for card manipulation
Implements shuffle and deal functionality
Demonstrates object composition
Time Management System
The Time class example shows:
Basic attribute management
Method implementation
Parameter handling
String formatting
Default value usage
2.11.2. Inheritance¶
Allows creation of new classes based on existing ones
Facilitates code reuse
Enables hierarchical class relationships
Can have drawbacks in code complexity
Attributes and Methods
Class Attributes:
Shared across all instances
Defined within class but outside methods
Useful for constants and class-wide data
Instance Attributes:
Specific to each object instance
Defined in init or other methods
Store object-specific data
2.12. Summary¶
Object-Oriented Programming in Python provides a powerful way to structure code through:
Class-based object creation
Attribute and method encapsulation
Inheritance for code reuse
Clear syntax for object manipulation