Mutability

Mutable objects have the ability to change their attributes after they are created.

One advantage of OOP is that our objects are mutable! This means that we can change the variables or attributes of any of our objects after instantiation. For example, Fido won’t be 5 years old forever, so we can manually change our dog’s age.

>>> fido.age = 6
>>> fido.age
6

As you can see above, when we call fido.age, the program will now return 6, not 5. We can also define a new method that can increment his age for us, so we don’t have to manually update it with 7, 8, 9...etc. forever. We use the self keyword once again to signify which specific object’s instance attribute we are changing.

def have_birthday(self): 
	self.age += 1	
	print(self.name + " is now " + str(self.age) + " years old. Happy birthday!!!")
	# str() converts integers into strings
	
>>> fido.have_birthday()
Fido is now 7 years old. Happy birthday!!!
>>> fido.age
7

Conclusion

In short, a python class defines a type of object. They define what attributes the object can have and what methods can be used to change the state of an object, and this method of programming is called object-oriented programming. OOP helps programmers cope with the complexity of large systems.

Last updated