Recall & Review
beginner
What does it mean to modify an object's state in Python?
Modifying an object's state means changing the values stored in its attributes. It's like updating the details of a real-world object, such as changing the color of a car or the balance in a bank account.
Click to reveal answer
beginner
How do you change an attribute value of an object in Python?
You access the attribute using dot notation and assign a new value. For example, if you have an object 'car' with attribute 'color', you can write: car.color = 'red' to change its color.
Click to reveal answer
intermediate
Why is it useful to have methods that modify an object's state?
Methods that modify state help keep changes organized and controlled. They can check if new values are valid before changing attributes, like making sure a bank account balance never goes negative.
Click to reveal answer
intermediate
What is the difference between modifying an object's state and reassigning the object variable?
Modifying state changes the data inside the object without creating a new object. Reassigning the variable makes it point to a completely new object. Modifying keeps the same object identity.
Click to reveal answer
beginner
Example: Given a class BankAccount with attribute balance, how would you add a method to deposit money?You define a method like this:
def deposit(self, amount):
if amount > 0:
self.balance += amount
This method changes the balance attribute by adding the deposit amount.Click to reveal answer
What does
self.balance = 100 do inside a method?✗ Incorrect
Using
self.balance = 100 sets or updates the balance attribute of the current object.Which of these changes the state of an object?
✗ Incorrect
Changing an attribute value directly modifies the object's state.
Why might you use a method to change an attribute instead of changing it directly?
✗ Incorrect
Methods can include checks to ensure the new value is acceptable, preventing errors.
What happens if you reassign an object variable to a new object?
✗ Incorrect
Reassigning changes the variable to refer to a new object; the old object remains unless no references point to it.
In a class, which keyword refers to the current object inside a method?
✗ Incorrect
In Python,
self is used inside methods to refer to the current object.Explain how you can change the state of an object in Python and why it is useful.
Think about updating details of something you own, like changing your phone's wallpaper.
You got /4 concepts.
Describe the difference between modifying an object's state and assigning a new object to a variable.
Consider the difference between repainting a car and buying a new car.
You got /3 concepts.