Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo
Introduction to Python Programming

11.2 Classes and instances

Introduction to Python Programming11.2 Classes and instances

Learning objectives

By the end of this section you should be able to

  • Create a class with instance attributes, class attributes, and the __init__() method.
  • Use a class definition to create class instances to represent objects.

Classes and instances

In the previous section, a real-world entity, like a person's social media profile, was modeled as a single object. How could a programmer develop a software system that manages millions of profiles? A blueprint that defines the fields and procedures of a profile would be crucial.

In a Python program, a class defines a type of object with attributes (fields) and methods (procedures). A class is a blueprint for creating objects. Individual objects created of the class type are called instances.

Checkpoint

Representing a coffee order with a class

Concepts in Practice

Classes and instances

Consider the example below:

    class Cat:
      def __init__(self):
        self.name = 'Kitty'
        self.breed = 'domestic short hair'
        self.age = 1
      def print_info(self):
        print(self.name, 'is a ', self.age, 'yr old', self.breed)
    
    pet_1 = Cat()
    pet_2 = Cat()
    
1.
What is the name of the class?
  1. Cat
  2. class Cat
  3. self
2.
Which of the following is an instance of the Cat class?
  1. __init__
  2. name
  3. pet_1
3.
Which of the following is an attribute?
  1. breed
  2. pet_2
  3. print_info
4.
Suppose the programmer wanted to change the class to represent a pet cat. Which is the appropriate name that follows PEP 8 recommendations?
  1. petcat
  2. pet_cat
  3. PetCat

Creating instances with __init__()

___init___() is a special method that is called every time a new instance of a class is created. self refers to the instance of a class and is used in class methods to access the specific instance that called the method. __init__() uses self to define and initialize the instance's attributes.

Checkpoint

Creating multiple coffee orders and changing attributes

Concepts in Practice

instances and __init__()

Consider the example below:

1
class Rectangle:
2
  def __init__(self):
3
    self.length = 1
4
    self.width = 1
5
  def area(self):
6
    return self.length * self.width
7
8
room_1 = Rectangle()
9
room_1.length = 10
10
room_1.width = 15
11
print("Room 1's area:", room_1.area())
12
room_3 = Rectangle()
13
room_3.length = 12
14
room_3.width = 14
15
print("Room 3's area:", room_3.area())
5.
How many times is __init__() called?
  1. 1
  2. 2
  3. 3
6.
When line 11 executes, execution flow moves to line 5. What does self represent on line 5?
  1. the area of room_1
  2. the instance room_1
  3. the Rectangle class
7.
Which line initializes the instance attribute length?
  1. 3
  2. 6
  3. 9
8.
Suppose line 2 is changed to def __init__():. What would room_1's attributes be initialized to?
  1. length = 0, width = 0
  2. length = 1, width = 1
  3. Error

Instance attributes vs. class attributes

The attributes shown so far have been instance attributes. An instance attribute is a variable that is unique to each instance of a class and is accessed using the format instance_name.attribute_name. Another type of attribute, a class attribute, belongs to the class and is shared by all class instances. Class attributes are accessed using the format class_name.attribute_name.

Checkpoint

Using class attributes for shared coffee order information

Concepts in Practice

Instances and class attributes

Consider the example above.

9.
Which is an instance attribute?
  1. loc
  2. order_id
  3. order_3
10.
Suppose the line order_1.cup_size = 8 is added before order_3.print_order(). What is the new output?
  1. Cafe Coffee Order 3 : 8 oz
  2. Cafe Coffee Order 3 : 16 oz
  3. Error
11.
Suppose the line CoffeeOrder.loc = 'Caffeine Cafe' is added before order_3.print_order(). What is the new output?
  1. Caffeine Cafe Order 3 : 16 oz
  2. Cafe Coffee Order 3 : 16 oz
  3. Error
12.
Suppose the line self.cls_id = 5 is added to the end of __init__()'s definition. What is the new output?
  1. Cafe Coffee Order 5 : 16 oz
  2. Cafe Coffee Order 3 : 16 oz
  3. Error

Try It

Creating a class for an airline's flight tickets

Write a class, FlightTicket, as described below. Default values follow the attributes. Then create a flight ticket and assign each instance attribute with values read from input.

Instance attributes:

  • flight_num: 1
  • airport: JFK
  • gate: T1-1
  • time: 8:00
  • seat: 1A
  • passenger: unknown

Class attributes:

  • airline: Oceanic Airlines
  • airline_code: OA

Method:

  • __init__(): initializes the instance attributes
  • print_info(): prints ticket information (provided in template)

Given input:

    2121
    KEF
    D22B
    11:45
    12B
    Jules Laurent
    

The output is:

    Passenger Jules Laurent departs on flight # 2121 at 11:45 from KEF D22B in seat 12B
    

Try It

Creating a class for fantasy books

Write a class, Book, as described below. Then create two instances and assign each instance attribute with values read from input.

Instance attributes:

  • title: ''
  • author: ''
  • year: 0
  • pages: 0

Class attribute:

  • imprint: Fantasy Tomes

Method:

  • __init__(): initializes the instance attributes
  • print_info(): prints book information (provided in template)

Given input:

    Lord of the Bracelets
    Blake R. R. Brown
    1999
    423
    A Match of Thrones
    Terry R. R. Thomas
    2020
    761
    

The output is:

    Lord of the Bracelets by Blake R. R. Brown published by Fantasy Tomes
    in 1999 with 423 pages
    A Match of Thrones by Terry R. R. Thomas published by Fantasy Tomes
    in 2020 with 761 pages
Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Feb 26, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.