Objects are mutable

20-minute lesson · module-classes-deeper-02

You are previewing this course as a guest

Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.

Sign in

Objects are mutable

20-minute lesson · module-classes-deeper-02

  • Mutate an object's attributes through a method that changes self.
  • Explain that passing an object to a function passes a reference, so mutations stick.
  • Distinguish a method that mutates in place from one that returns a new object.
  • Predict the effect of mutating a shared object reference.

Source attribution

Status: adapted

How to Think Like a Computer Scientist: Interactive Edition source · Classes and Objects - Digging a Little Deeper / Objects are Mutable

Adaptation notes. Reading rewritten in our voice. A Rectangle class grows and moves via mutating methods, and a function mutates a Rectangle passed to it. Hidden tests check in-place mutation and that a function's changes are visible to the caller.

License notes. Original chapter is GNU FDL 1.3 (Brad Miller and David Ranum). No verbatim text from the original is reproduced here.