Convert Method to an Attribute
In the previous lesson, you set up the
.is_hungry() method that works well to figure out whether the animal is hungry or not. But it seems like actually calling a method for just getting this information, whether it’s hungry or not, feels a little overkill.
What I want to do instead is be able to treat this as an attribute as if it was one of those attributes, which
.is_hungry() is a proxy for
._stuff_in_belly, but I’m really just interested whether they’re hungry or not, not how much they have in their belly,
but it feels nice for this to be an attribute. So what you can do in this case is you can use a decorator that’s a built-in decorator. So you can say
@property at the top of any method inside of your class, and that’s going to make Python pretend that something that is actually a method is an attribute.
So you’ll be able to address it as if it was an attribute, but it’s really a method that does a small calculation in its function body to figure out a value. Using a
@property makes sense in a situation like this where the calculation that you do inside of the method is actually relatively small and not very expensive, and you just want to have a publicly accessible aspect of your class to be easier to deal with. Let’s try it out.
So I’m treating
.is_hungry like an attribute. And here I’m getting back
True because Lizzy didn’t eat yet, but now I can make Lizzy eat three times, and you’ll see that the functionality is the same as before. If it has more than two in its non-public
._stuff_in_belly attribute, then
So it’s exactly the same functionality as before. The only difference is that you don’t need to explicitly call it, and it’s kind of treated like an attribute, and that’s the idea of using the
@property decorator. If you haven’t heard of decorators before, you can look at other resources that we have. I’m also going to link some.
There are ways to modify functions in Python. Basically, it’s a pretty interesting topic, but it’s a little advanced. So at this point, if you’re just interested in learning more about object-oriented programming, you can also just keep in mind that you can put this
@property at the top of any method definition inside of your class. And then what it’s going to do is, it’s going to pretend that the method that you defined in here is an attribute.
Again, this only makes sense if it’s a pretty small method that does just a small calculation like in this case. Otherwise, it’s probably better to be explicit and make it clear to your users that they’re actually calling a method. All right, but for this, I think it’s pretty nice and it makes it a little neater to interact with. Also for the rest of the code, in case we’re going to rely in some ways on this
.is_hungry, which I think we should,
Become a Member to join the conversation.