Skip to main content
Engineering LibreTexts

14.8: Many Instances

  • Page ID
    8697
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\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}}\)

    So far, we have been defining a class, making a single object, using that object, and then throwing the object away. But the real power in object oriented happens when we make many instances of our class.

    When we are making multiple objects from our class, we might want to set up different initial values for each of the objects. We can pass data into the constructors to give each object a different initial value:

    Code 14.8.1 (Python)
    %%python3
    
    class PartyAnimal:
       x = 0
       name = ''
       def __init__(self, nam):
         self.name = nam
         print(self.name,'constructed')
    
       def party(self) :
         self.x = self.x + 1
         print(self.name,'party count',self.x)
    
    s = PartyAnimal('Sally')
    j = PartyAnimal('Jim')
    
    s.party()
    j.party()
    s.party()
    
    # Code: http://www.py4e.com/code3/party5.py
    
    

    The constructor has both a self parameter that points to the object instance and then additional parameters that are passed into the constructor as the object is being constructed:

    s = PartyAnimal('Sally')

    Within the constructor, the line:

    self.name = nam

    Copies the parameter that is passed in (nam) into the name attribute within the object instance.

    The output of the program shows that each of the objects (s and j) contain their own independent copies of x and nam:

    Sally constructed
    Sally party count 1
    Jim constructed
    Jim party count 1
    Sally party count 2

    This page titled 14.8: Many Instances is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Chuck Severance.

    • Was this article helpful?