Classes Vs Objects

Fred Agbo

October 28, 2026

Happy Wednesday!

  • Class grouping today: Scan the QR code or go to https://tools.jedrembold.prof/daily
  • Class code is ZvG9U
  • Introduce yourselves! Tell your friend your favorite CLASS assignments?

Quick Announcements

  • Project ImageShop is ongoing and due next week Monday
    • Again, begin to work on it from tomorrow to remain on target
    • Section meeting this week will provide more useful tools on the project
  • Second midterm exam is next week Friday 6th of November.
    • More details next week

Classes vs Objects

  • When we introduced PGL early in the semester, we stressed the difference between types/classes and objects
    • A class is the pattern or template that defines the structure and behavior of values with that particular type (the species of ant)
    • An object is an individual value that belongs to a class (an individual ant)
      • A single class can be used to create any number of objects, each of which is said to be an instance of that class
  • PGL defines the GRect class.
    • In Breakout, you used that class to create many different rectangles, each of which was an instance of the GRect class

Thinking about Objects

image/svg+xml GRect x1,y1,w,h set_color set_fill_color move get_width set_filled client abstractionboundary implementation
 

An Object’s Purpose

  • Python uses the concepts of objects and classes to achieve at least three different goals:
    • Aggregation. Objects make it possible to represent collections of independent data as a single unit. Such collections are traditionally called records.
    • Encapsulation. Classes make it possible to store data together with the operations that manipulate that data.
      • In Python the data values are called attributes and the operations are called methods
    • Inheritance. Class hierarchies make it possible for a class that shares some attributes and methods with a previously defined class to inherit those definitions without rewriting them all
  • We’ll introduce many of these concepts in this course, but for more exposure and practice you’ll want to take CS 152 (Data Structures)

Classes as Templates

  • Since they share the same attributes, it is natural to regard the two employees at Scrooge and Marley as two instances of the same class
  • Could view the class as a template or empty form:

  • Can help initially to just start with an empty template and then fill in the necessary fields

Starting Empty

  • Class definitions in Python start with a header line consisting of the keyword class and then the class name

  • The body of the class will later contain definitions, but initially can just leave blank

    • Almost. Python does not allow an empty body, so need to include a docstring or use the pass keyword
    class Employee:
      """This class is currently empty!"""
  • Once the class is defined, you can create an object of this class type by calling the class as if it were a function:

    clerk = Employee()

More References

  • Instances of custom Python classes are mutable
  • Thus custom class instances are stored as references to that information in memory
  • Any code with access to this reference can manipulate the object
    • Can get or set the contents of any attributes or create new ones

Objects are references!

Selecting Object Attributes

  • You can select an attribute from an object by writing out the object name, followed by a dot and then the attribute name.

    • As an example

      clerk.name

      would select the name attribute for the clerk object

  • Attributes are assignable, so

    clerk.salary *= 2

    would double the clerk’s current salary

  • You can create a new attribute in Python by simply assigning a name and a value, just like you’d define a new variable

Assigning Clerk Attributes

  • We could, for instance, create a clerk in the following fashion:

    def create_clerk():
      clerk = Employee()
      clerk.name = "Bob Cratchit"
      clerk.title = "clerk"
      clerk.salary = 15
      return clerk
  • Note that none of these assigned attributes affect the Employee class in any way

More Generally

  • We could accomplish this more generally by passing arguments to our function:

    def create_employee(name, title, salary):
      emp = Employee()
      emp.name = name
      emp.title = title
      emp.salary = salary
      return emp
  • We could then use that as:

    clerk = create_employee('Bob Cratchit', 'clerk', 15)
    boss = create_employee(
              'Ebeneezer Scrooge', 'founder', 1000
              )

Constructors

  • While the previous method works, it is not ideal
    • Forces the client to tinker with the internal workings of the Employee
    • Details of the data structure are the property of the implementation, not the client
  • Better to add a method to the Employee class called a constructor, which is responsible for initializing attributes to a newly created object
    • In Python, a constructor is created by defining a special function named __init__
    • The constructor function is called automatically whenever a new object of that type is created

Know Thy self

  • Moving the function into the Employee class has a problem:
    • When we set attributes, they are specific to a given object
    • The class itself though is just a template, and not linked to a specific object
  • We need a general way within the class to refer to whatever object is being created
    • The overwhelming convention in Python is to call this variable self
    • Whenever a new object is created, you could imagine that, for that object, Python replaces all of the selfs in the class with that object’s name
      • This isn’t quite the order of what is happening, but it can help envision what self is doing
  • self is always the first parameter to the __init__ constructor
    • Any other arguments provided are passed in as additional parameters afterwards

An Employee Constructor

class Employee:
    def __init__(self, name, title, salary):
        self.name = name
        self.title = title
        self.salary = salary


clerk = Employee('Bob Cratchit', 'clerk', 15)
  • Note that you do not need to provide an argument for self when creating the object, Python supplies this reference automatically
  • Viewing in PythonTutor can be helpful, as is shown here

What’s your Method?

  • Most classes define additional functions called methods to allow clients to read or update attributes or manipulate the object

  • Methods look like a normal function definition but will always declare the parameter self at the beginning of the parameter list

    • This is true even if the method has no other parameters
  • Methods are defined in the body of the class and would thus look something like:

    def method_name (self, other_parameters):
      ...body of the method...
  • For example

    def give_raise(self, amount):
      self.salary += amount

Accessing and Using Methods

  • After definition, there are two mains ways you can access and use the method:
    • Dot Notation (Conventional)
      • Python sets self to be a reference to the receiver, which is the object to which the method is applied

        clerk = Employee('Bob', 'clerk', 15)
        clerk.give_raise(15)
    • Function Notation
      • You retrieve the method from the class itself, and then provide self manually

        clerk = Employee('Bob', 'clerk', 15)
        Employee.give_raise(clerk, 15)

Visualization Summary

  • To summarize in a visual manner, we can look at everything together on PythonTutor

Today’s Group Activities LO’s

  • Why would we create a custom data type?
  • What is the abstraction boundary, and why do we care?
  • How do we create a basic class?
  • How can we add attributes to a class in a constructor method?

–

Problem 1a: Review Tuple

What would be the output of the printed statement in the code to the right?

  1. (1, 'a', 'b')
  2. (1, 'a')
  3. Error: can’t add strings and tuples
  4. Error: index out of range
A = (1, 3, 5)
B = (2*A, ('a', ) )
C = B + ('b', 'c', 'd')
D = tuple()
for v in C[:3]:
    D += v[:1]
print(D)

–

Problem 1b: Tracing Cars

What is printed out on the final line of code to the right?

  1. Honda red 2006
  2. Honda blue 2006
  3. Toyota blue 2008
  4. Honda red 2008
class Car:
    def __init__(self, color, year):
        self.color = color
        self.year = year
        self.make = 'Toyota'

A = Car('blue', 2008)
A.make = 'Honda'
B = Car('red', 2006)
A.year = B.year
print(A.make, A.color, A.year)

Problem 2a: A Classy Song

  • This is a coding problem. Work in pairs or trios on a single computer, and discuss your algorithm BEFORE YOU WRITE ANY CODE.
  • Your task:
    • You want to define a class to hold information about a single song
    • You desire to store several attributes: title, artist, and duration_sec
    • Define the class and write the necessary constructor

Problem 2b: Genres

  • Swap who is typing!
  • Suppose you realized you also want to track genres in your class, and so add as an attribute
  • What data-type will the value be that is assigned to the genres attribute? You get to choose, but have a reason for why you chose what you did!
  • Implement this new attribute into your class

Problem 2b: Personal Taste

  • Swap who is typing!
  • For each member in your group, get at least two of their favorite songs
  • Create a song object for each song (look up values online as needed) and add them to a list called playlist

Problem 2d: Play Time

  • Swap who is typing!
  • Write a function that loops through each song in the playlist, and then prints the total playlist duration to the screen.
  • Bonus: Also print out all the different genres covered within the playlist
// reveal.js plugins