Opening the book…
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)
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 was last modified on Fri, 10 Sep 2021 02:10:03 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.
The book could not be loaded just now.