From the course: Python Practice: Object-Oriented Programming
Unlock this course with a free trial
Join today to access over 24,700 courses taught by industry experts.
Solution: Protect an attribute - Python Tutorial
From the course: Python Practice: Object-Oriented Programming
Solution: Protect an attribute
- [Instructor] Here's how I solved this challenge, and there's two things going on here that we need to recognize. First, we'll change the price attribute to start with an underscore. In Python, a leading underscore is a convention to say, even though you can access this, please don't, pretend it's not there, pretend it's private. Other languages make this more robust, but Python doesn't. And so, that's all we can do to sort of make a private attribute. Second, I added a method called price, which when called returns self._price, our semi-private attribute that stores the price of the item. However, above that, I added the at property decorator, which treats this method like the getter for a regular attribute. Ordinarily, when we define an attribute, it has a getter and setter method. In our case here, we don't want price to have a setter method. So we can use at property, which is a shorthand for basically only…