
PYTHON — Public Location Property in Python
Simplicity is the soul of efficiency. — Austin Freeman
Adding a Public Location Property in Python
In this tutorial, we’ll learn how to add a public location property to a Python class using the example of a farm simulation. The public location property will allow us to access the location of an animal in a readable format. We’ll achieve this by introducing a new instance method and making it a property to calculate and return the location based on the non-public location attribute of the instance.
Code Example
Below is a Python class representing an animal in a farm simulation:
class Animal:
def __init__(self, name, color, mood):
self.name = name
self.color = color
self.mood = mood
self._location = None # Non-public location attribute
@property
def location(self):
return self._location.location_type if self._location is not None else "void"
def move(self, new_location):
self._location = new_location
def __str__(self):
return f"The {self.mood} {self.color} dog {self.name} jumps in the {self.location}"In the Animal class, we have defined a private attribute _location to store the location of the animal. We also have a location property that calculates the location based on the _location attribute and returns a readable location type. This property allows us to access the location of an animal object as if it were an attribute.
Usage
Let’s create an instance of the Animal class and test the public location property:
class Location:
def __init__(self, location_type):
self.location_type = location_type
field = Location("field")
dog = Animal("Puppy", "black", "happy")
dog.move(field)
print(dog) # Output: The happy black dog Puppy jumps in the field
new_dog = Animal("Fido", "black", "happy")
print(new_dog) # Output: The happy black dog Fido jumps in the voidIn this usage example, we create instances of the Animal class and a Location class. We then move the animals to different locations and print their locations using the public location property.
Summary
In this tutorial, we learned how to add a public location property in a Python class. We used the example of a farm simulation to demonstrate how to create a property that calculates and returns the location of an animal in a readable format. This allows for easy access to the location information and enhances the usability of the class.






