Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

11.2: Classes and Instances

( \newcommand{\kernel}{\mathrm{null}\,}\)

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
  • class Cat
  • 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
  • order_id
  • 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

    This page titled 11.2: Classes and Instances is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.

    Support Center

    How can we help?