Add Public Location Property
It’ll calculate the location based on
self._location, the non-public location attribute that I have on an instance. Essentially, I want it to return
self._location.location_type, but only if
self._location is not
I’ve also decided to make it a property so that you can then access it on an animal object just like you would an attribute. But it does this, a little bit of logic in there that doesn’t return the location object that I’m storing in
self._location, but actually just a string that’s readable.
And that also allows me to change the f-string inside of
.__str__() to just point to
self._location, which is now going to be the
location() property that I defined here, at least in theory. Let’s go try it out.
move the dog, probably move to the field, and then print
The happy black dog Puppy jumps in the field. That sounds good. What if I have a new instance of
Dog that hasn’t moved anywhere yet?
The happy black dog Fido jumps in the void. Okay, so now whether or not the
._location attribute points to
None or a
FarmLocation instance, I get a readable output, and I’ve also introduced a new property
02:52 I’m happy with that. So here I’ve improved a bit the string representation, the output, and introduced another property. And that’s not an uncommon way of working with properties, where you have a non-public attribute of the same name basically that you only use internally.
And that is a little different than the one that you want to show to the users of your module. And in this case, the
._location attribute that I’m using should ideally point to a location object.
And you don’t really want your users to see the location object, which is why in the public
location() property, you do a bit of logic by only exposing the
.location_type of that location object.
Become a Member to join the conversation.