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: Agnes Hekler
2.7.1. Overview¶
Today’s class was an introduction to object-oriented programming in Python. During the lecture we covered:
Classes, objects, class methods and the
__init__methodInheritance and the concept of child and parent classes
Tuples and their uses
Example code in Python 4a and Python 4b Jupyter notebooks
Python 4a: Tuples and their uses
Python 4b: Classes and objects, classes and functions, classes and methods, and inheritance
Note: It is recommended to go through both of these notebooks to ensure all concepts are understood.
2.7.2. Classes and Objects¶
A class is a programmer defined type that serves as a blueprint for creating objects. It defines the attributes and methods that all of the class objects will share.
These are very useful for grouping related data in a program together increasing program organization and readability.
Attributes represent the properties that a class contains. For example, the class Car can have attributes such as make and model.
Methods are functions that are defined within a class, that describe what the class will do. For example, the class Car may have a method called stop_driving.
When creating an object/instance of a class, it then contains all the attributes and methods associated with the class.
Classes are especially useful when creating multiple objects, as it allows for code to be reused and makes relationships within the code clear, increasing its readability. For example the objects Jetta and Golf can be created from the class Car. This provides Jetta and Golf with the attributes and methods of the class Car, without needing to rewrite them. It also clearly represents that they are both instances of the class Car.
Additional examples of classes, methods, and attributes are provided in the subsequent sections.
Reference: Python Classes and Objects, https://www.w3schools.com/python/python_classes.asp
Example: Defining a class in Python:
class Point:
"""Represents a point in 2-D space"""
The name of this class is “Point” and it contains a docstring explaining its purpose.
When creating a new object of a class, it is referred to as an instantiation.
Example: Creating an instance of Point:
blank = Point()
Attributes can be assigned to an object using dot notation, and accessed in the same way.
Example: Assigning and accessing attributes:
class Point:
x = 0.0
y = 0.0
blank = Point()
blank.x = 3.0
blank.y = 4.0
print("Value of x:", blank.x)
print("Value of y:", blank.y)
2.7.3. Classes and Functions¶
In this section we were introduced to functions that take a class object as a parameter.
These functions are defined outside the class body, which differentiates them from class methods (covered in section 2.7.4).
Once an object of the class is created, it can be passed to these functions, providing them with access to all of the object’s attributes.
While this approach is useful, it can be difficult to follow the connection between the functions and class since they are not defined within the class itself.
Example:
class Time:
"""Represents the time of day.
attributes: hour, minute, second
"""
hour = 0
minute = 0
second = 0
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
def print_time(time):
print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))
print_time(time)
In the example above, a class called Time with the attributes hour, minute and second is defined.
An object, time, of class Time is created, and values are assigned to its attributes.
The object time is then passed to the function print_time, which uses the object’s attributes to display the start time.
2.7.4. Classes and Methods¶
A method is a function that is associated with a specific class.
The main difference between a method and a function is that methods are defined within the body of a class.
This helps keep class specific code organized within the class definition, making it easier to follow.
Example:
class Time:
"""Represents the time of day.
attributes: hour, minute, second
"""
hour = 0
minute = 0
second = 0
def print_time(time):
print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
time.print_time()
In the example above, the print_time function was rewritten as a method.
The key difference is that the function is now defined inside the body of the class, and the method is called using the dot notion.
Init Method
The
__init__method (also called the constructor) in a class is used to initialize the attributes of a new object.The first parameter, self refers to the new object of the class, while the additional parameters are used to set the initial attribute values.
When creating a new object, the
__init__method of the class is automatically called to set the parameters.
Example:
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
time = Time(9, 45)
In the example above, the hour and minute attributes are initialized to 9 and 45, while second uses the default value of 0.
2.7.5. Inheritance¶
Inheritance allows for a new class to be defined based on an existing one.
The new (child) class inherits the attributes and methods of the existing (parent) class.
This is a very useful concept because it avoids needing to create a new class with many of the same methods and attributes, reducing code duplication.
Inheritance also helps shows the relationship between related classes.
An example of this is provided in the code below.
Example:
class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def pop_card(self):
# deals from the bottom of the deck
return self.cards.pop()
def add_card(self, card):
self.cards.append(card)
class Hand(Deck):
"""Represents a hand of playing cards."""
def __init__(self, label=''):
self.cards = []
self.label = label
In this example, the Hand class inherits from the parent Deck.
Since a hand is similar to a deck (they both are made of cards and need functionality for adding and removing cards), it makes sense for Hand to inherit the methods and attributes from Deck.
By inheriting from Deck, Hand objects can use functions such as
pop_cardandadd_cardand also have thecardsattribute.Since the Hand class contains its own
__init__method, the attributes such cards and label could be set up specifically for Hand (cards is now an empty list and the new attribute label was added).The built-in
__str__method defines what is displayed when an object is printed.
Note: Inheritance can become hard to read so make sure to include good comments.
2.7.6. Tuples¶
Tuples are a sequence of values that can be of any type (ex.
int, string, float).
They are very similar to lists, but differ in the sense that they are immutable.
This means that tuples cannot be changed after they are created.
Example: Defining a tuple:
t1 = ('a', 'b', 'c', 'd', 'e')
t2 = 'a',
A tuple (ex. t1) is defined as a comma-separated list of values.
A tuple of a single element (ex. t2) is defined the same but needs to include a trailing comma.
The slice operator can be used the same way as with lists.
Tuples don’t support item assignment so they cannot be changed, but they can be replaced.
Note: Think of a tuple as a sealed box, you can look at its content but cannot change what is inside (ex. RGB, xyz coordinates).
Example: Replacing a tuple element:
t = ('A',) + t[1:]
Tuple assignments are often used to swap the values of two variables.
Other uses for Tuples
Can be used as return values, allowing for multiple values to be returned at once.
Dictionary items can be returned as a sequence of key-value pair tuples.
Can use built-in functions such as divmod and sum.
Note: Refer to W3Schools for examples of Python built-in functions and syntax
See example reference from W3Schools for sum function:
https://www.w3schools.com/python/ref_func_sum.asp