Skip to main content
Engineering LibreTexts

11.3: Instance Methods

  • Page ID
    117594
  • \( \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 and implement __init__() with multiple parameters including default parameter values.
    • Describe what information an instance method has access to and can modify.

    More about __init__()

    In Python, __init__() is the special method that creates instances. __init__() must have the calling instance, self, as the first parameter and can have any number of other parameters with or without default parameter values.

    Checkpoint: Creating patient vital signs instances
    Concepts in Practice: Defining and using __init__() with parameters

    Consider the example above.

    Concepts in Practice \(\PageIndex{1}\): Defining and using __init__() with parameters

    Suppose the programmer wanted to make blood pressure a required parameter in __init__(). Which is the correct __init__() method header?

    1. def __init__(p_id, bp, self, tmp=-1.0, hr=-1, rr=-1):
    2. def __init__(self, p_id, bp, tmp=-1.0, hr=-1, rr=-1):
    3. def __init__(self, p_id, bp=[-1,-1], tmp=-1.0, hr=-1, rr=-1):
    Answer

    b. Removing the default parameter value makes bp a required parameter.

    Concepts in Practice \(\PageIndex{2}\): Defining and using __init__() with parameters

    Which is a correct call to __init__() to create an instance with p_id=5241?

    1. patient_10 = Vitals(self, 5241)
    2. patient_10 = Vitals(5241)
    3. both
    Answer

    b. self is the first parameter in __init__() definition, not an explicit argument. self should not be included in the call.

    Concepts in Practice \(\PageIndex{3}\): Defining and using __init__() with parameters

    Suppose another __init__() definition is added after the first with the header as follows:

    def __init__(self, p_id, bp, tmp, hr, rr)

    What is the impact on the program?

    1. no change.
    2. Second __init__() definition produces an error.
    3. First two __init__() calls produce an error.
    Answer

    c. The second definition overwrites the first as multiple explicit definitions of __init__() aren't allowed. __init__() requires all parameters, so the first two __init__() calls for patient_1 and patient_2 are incorrect.

    Instance methods

    An instance method is used to access and modify instance attributes as well as class attributes. All methods shown so far, and most methods defined in a class definition, are instance methods.

    Example 11.1: Instance methods are often used to get and set instance information
      class ProductionCar:
        def __init__(self, make, model, year, max_mph = 0.0):
          self.make = make
          self.model = model
          self.year = year
          self.max_mph = max_mph
    
        def max_kmh(self):
          return self.max_mph * 1.609344
    
        def update_max(self, speed):
          self.max_mph = speed
    
      car_1 = ProductionCar('McLaren', 'Speedtail', 2020) # car_1.max_mph is 0.0
      car_1.update_max(250.0) # car_1.max_mph is 250.0
      print(car_1.make, car_1.model, 'reaches', car_1.max_mph, 'mph (',
        car_1.max_kmh(), 'km/h)') # Prints McLaren Speedtail reaches 250.0 mph (402.336 km/h)
      
    Concepts in Practice: CoffeeOrder instance methods

    Consider the example below:

      class CoffeeOrder:
        loc = 'Cafe Coffee'
        cls_id = 1
    
        def __init__(self, size=16, milk=False, sugar=False):
          self.order_id = CoffeeOrder.cls_id
          self.cup_size = size
          self.with_milk = milk
          self.with_sugar = sugar
          CoffeeOrder.cls_id += 1
    
        def change(self, milk, sugar):
          self.with_milk = milk
          self.with_sugar = sugar
    
        def print_order(self):
          print(CoffeeOrder.loc,'Order', self.order_id, ':', self.cup_size, 'oz')
          if self.with_milk:
            print('\twith milk')
          if self.with_sugar:
            print('\twith sugar')
      
      order_1 = CoffeeOrder(8)
      order_2 = CoffeeOrder(8, True, False)
      order_1.change(False, True)  
    
    Concepts in Practice \(\PageIndex{4}\)

    What does order_1 represent at the end of the program?

    1. 8 oz coffee
    2. 8 oz coffee with milk
    3. 8 oz coffee with sugar
    Answer

    c. order_1 is originally a coffee without milk or sugar, but the call to change() adds sugar to the order by assigning order_1.with_sugar with True .

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

    Why is change() an instance method?

    1. can change attributes
    2. has multiple parameters
    3. can change an instance
    Answer

    c. An instance method's first parameter indicates the method can change an instance. change() allows a change in whether a coffee order has milk or sugar.

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

    Can print_order() be unindented?

    1. yes
    2. no
    Answer

    b. Unindenting print_order() would produce an error. An instance method must be defined in the class.

    Try It: Creating a class for vending machines

    Write a class, VendingMachine, as described below. Default values follow the attributes. Ex: count's default value is 0. Create a vending machine using a value read from input and call instance methods.

    Instance attributes:

    • count: 0
    • max: 0

    Methods:

    • __init__(num): initializes count and max with num parameter
    • refill(): assigns count with max's value and prints "Refilled"
    • sell(order): assigns count with the value of count minus order and prints "Sold: [order]"
    • print_stock(): prints "Current stock: [count]"

    Given input:

      100
      25
    

    The output is:

      Current stock: 100
      Sold: 25
      Current stock: 75
      Refilled
      Current stock: 100
    
    Interactive Code
    # Define VendingMachine class 
    
    stock = int(input())
    vm = VendingMachine(stock)
    vm.print_stock()
    order_1 = int(input())
    vm.sell(order_1)
    vm.print_stock()
    vm.refill()
    vm.print_stock()
    
     
    Input

    80
    50

    Answer

    class VendingMachine:
    def __init__(self, num):
    self.count = num
    self.max = num

    def refill(self):
    self.count = self.max
    print('Refilled')
    def sell(self, order):
    self.count -= order
    print('Sold:', order)
    def print_stock(self):
    print('Current stock:', self.count)

    stock = int(input())
    vm = VendingMachine(stock)
    vm.print_stock()
    order_1 = int(input())
    vm.sell(order_1)
    vm.print_stock()
    vm.refill()
    vm.print_stock()


    This page titled 11.3: Instance Methods 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.