Skip to main content
Engineering LibreTexts

11.2: Classes and Instances

  • Page ID
    117593
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

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

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

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

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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()
    
    Concepts in Practice \(\PageIndex{1}\)

    What is the name of the class?

    1. Cat
    2. class Cat
    3. self
    Answer

    a. Cat follows the class keyword at the top of the class definition and is the name of the class.

    Concepts in Practice \(\PageIndex{2}\)

    Which of the following is an instance of the Cat class?

    1. __init__
    2. name
    3. pet_1
    Answer

    c. pet_1 is an instance of the Cat class created by calling Cat(). The other instance is pet_2.

    Concepts in Practice \(\PageIndex{3}\)

    Which of the following is an attribute?

    1. breed
    2. pet_2
    3. print_info
    Answer

    a. breed is an instance attribute defined in __init__(). The other instance attributes are name and age.

    Concepts in Practice \(\PageIndex{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
    Answer

    c. CapWords style, with all words capitalized and no spaces between words, is recommended for class names. "Pet" and "cat" are separate words, so each is capitalized and one directly follows the other.

    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())

    Concepts in Practice \(\PageIndex{5}\)

    How many times is __init__() called?

    1. 1
    2. 2
    3. 3
    Answer

    b. Two instances, room_1 and room_3, are created by calling Rectangle(), which calls the constructor __init__().

    Concepts in Practice \(\PageIndex{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
    Answer

    b. room_1 is the instance that called the method area(), so self represents the specific instance.

    Concepts in Practice \(\PageIndex{7}\)

    Which line initializes the instance attribute length?

    1. 3
    2. 6
    3. 9
    Answer

    a. Line 3 is in __init__(), which initializes length and the other instance attributes for each new instance.

    Concepts in Practice \(\PageIndex{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
    Answer

    c. __init__() has one required parameter, conventionally called self, which allows the constructor to access the instance.

    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.

    Concepts in Practice \(\PageIndex{9}\)

    Which is an instance attribute?

    1. loc
    2. order_id
    3. order_3
    Answer

    b. order_id is an instance attribute defined in __init__(). The other instance attribute is cup_size.

    Concepts in Practice \(\PageIndex{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
    Answer

    b. Changing order_1.cup_size does not affect order_3.cup_size. order_1.cup_size changes to 8 and order_3.cup_size is still 16 .

    Concepts in Practice \(\PageIndex{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
    Answer

    a. order_1, order_2, and order_3 all share the class attribute CoffeeOrder.loc. Changing loc affects all instances, so Caffeine Cafe is printed as the location.

    Concepts in Practice \(\PageIndex{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
    Answer

    b. Trying to access a class attribute using an instance is unsafe. In __init__(), trying to access the class attribute creates a new instance attribute called cls_id. Though possible, programmers should avoid using the same name for class attributes and instance attributes to avoid confusion.

    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.