From the course: Getting Started with Python Object Oriented Programming: A Hands-On Approach

Unlock the full course today

Join today to access over 23,200 courses taught by industry experts.

Solution: Getters and setters

Solution: Getters and setters

(upbeat music) - [Instructor] Here's my solution to the challenge for this chapter. Yours should look similar. So in our method set_balance, we need to have a condition. So if the balance, now, this is the balance that's being passed in as an argument on line 27, if it is greater than or equal to zero, then we go ahead and we update the balance. And remember it's _balance because we want to express the intention that this is a private variable. So self._balance equals the balance that gets passed into the setter method. However, if a negative value is passed in, so that means the condition on line 28 is not met, then we print an error message. "Error: Balance must be a non-negative." Okay, so let's see if it works. On line 44, we're updating the balance to 6000, and you can see that it has in fact become 6000 down in the console. And let's try a negative value as well just to check that. So I'm going to copy that code, paste it. And let's try and make it -6000. And you can see that we…

Contents