From the course: Python Practice: Object-Oriented Programming

Unlock this course with a free trial

Join today to access over 24,900 courses taught by industry experts.

Solution: Add a method to a class

Solution: Add a method to a class

- [Instructor] To solve this challenge, we need to create a way of keeping track of how many slices remain. So here in the initializer, I'll set self.slices remaining to the value of slices when the instance is created. Then I'll define the method sell, which takes self as an argument because it's an instance method and I'll add the variable count to represent how many slices are being sold when the method is called. Within this method, we'll run a few checks. First, we'll see if the count of slices being sold is less than or equal to zero. If it is, we'll return the string that says we can't sell zero or negative slices, and we won't do anything to the value of self.slices remaining. Next, we'll check whether subtracting the count of slices sold from our slices remaining would result in a negative number. If it does, we'll return the string that says we can't sell more slices than we have. It's fine if this…

Contents