This project guides you through building a Dog class in Python, demonstrating core Object Oriented Programming (OOP) concepts such as instance attributes, methods, and properties. The Dog model simulates a veterinary clinic’s database tool to manage client information.
In this lesson, you will create a Dog class that models the essential attributes and behaviors of a dog in a veterinary setting. You will learn how to:
- Define a class and initialize instance properties
- Implement instance methods to modify object state
- Use Python properties to add validation logic to attributes
- Create and interact with class instances
This exercise provides a practical introduction to OOP fundamentals in Python.
By the end of this lesson, you will be able to:
- Define a Python class with appropriate attributes and methods
- Initialize class instances with default and required parameters
- Create instance methods that modify object state
- Implement getter and setter methods using Python properties
- Validate attribute values within setters to enforce data integrity
- Understand the use of
selfand instance-specific data - Work with feature branches and Git workflow for collaborative development
- Python 3.x
- pipenv for dependency management and virtual environment
Follow these steps to set up your environment:
-
Fork and Clone the Repository
- Navigate to the GitHub Repo.
- Fork the repository to your GitHub account.
- Clone your fork locally:
git clone <your-forked-repo-url> cd python-oop1-technical-lesson
-
Install Dependencies
- Run the following commands to install dependencies and activate the virtual environment:
pipenv install pipenv shell
- Run the following commands to install dependencies and activate the virtual environment:
-
Open the Project
- Open the project folder in your preferred code editor (e.g., VSCode).
To run the Dog class demonstration:
python lib/dog.pyThis will execute the script that creates Dog instances, invokes methods, and demonstrates property validation.
When running the script, you should see the following output in your terminal:
3
Fido is turning 4
4
None
Checking up with Clifford on 03/02/2024
03/02/2024
Not valid age
Not valid age
The Dog class includes:
-
Attributes:
name(string): Dog’s namebreed(string): Dog’s breedage(int): Dog’s age, validated to be a non-negative integerlast_checkup(string or None): Date of last checkup
-
Methods:
checkup(date): Updates thelast_checkupdate and prints a messagebirthday_celebration(): Increments the dog’s age by 1 and prints a celebratory message
-
Property:
age: Uses getter and setter to enforce that age is an integer ≥ 0. Invalid assignments print an error message.
Follow this workflow for development:
-
Create a feature branch:
git checkout -b dog_class
-
Make your changes and commit with a descriptive message:
git commit -am "Finish Dog model" -
Push the branch to GitHub:
git push origin dog_class
-
Open a Pull Request (PR) on GitHub, review, and merge into the main branch.
-
Pull the latest main branch and delete the feature branch locally:
git checkout main git pull origin main git branch -d dog_class
If deletion fails because Git doesn’t recognize the branch as merged, force delete with:
git branch -D dog_class
- Code Comments: Add comments to clarify code intent and improve maintainability.
- Understanding Instances and
self: Each instance has its ownselfcontext; this is fundamental to OOP. - Property Underscores: Use an underscore prefix (e.g.,
_age) in getter/setter to avoid recursive calls. - Validation: Use property setters to enforce data integrity and prevent invalid attribute values.
Create a new branch for your work:
git checkout -b dog_classDefine a basic Dog class:
class Dog:
passClasses in Python start with the class keyword, followed by the class name capitalized and a colon.
Add the __init__ method to initialize attributes when creating an instance:
class Dog:
def __init__(self, name, breed, age, last_checkup=None):
self.name = name
self.breed = breed
self.age = age
self.last_checkup = last_checkupselfrefers to the instance being created.last_checkupdefaults toNoneif no value is provided.
Add methods to perform actions on instances:
class Dog:
def __init__(self, name, breed, age, last_checkup=None):
self.name = name
self.breed = breed
self.age = age
self.last_checkup = last_checkup
def checkup(self, date):
print(f"Checking up with {self.name} on {date}")
self.last_checkup = date
def birthday_celebration(self):
self.age += 1
print(f"{self.name} is turning {self.age}")checkupupdateslast_checkupand prints a message.birthday_celebrationincrements age and prints a celebratory message.
Instantiate Dog objects and interact with them:
fido = Dog("Fido", "Golden Retriever", 3, "05/22/2022")
clifford = Dog(
name="Clifford",
age=2,
breed="Big Red"
)
print(fido.age)
fido.birthday_celebration()
print(fido.age)
print(clifford.last_checkup)
clifford.checkup("03/02/2024")
print(clifford.last_checkup)fidouses positional arguments.clifforduses keyword arguments for clarity and flexibility.
Add getter and setter for age to validate input:
class Dog:
def __init__(self, name, breed, age, last_checkup=None):
self.name = name
self.breed = breed
self.age = age
self.last_checkup = last_checkup
def checkup(self, date):
print(f"Checking up with {self.name} on {date}")
self.last_checkup = date
def birthday_celebration(self):
self.age += 1
print(f"{self.name} is turning {self.age}")
def get_age(self):
return self._age
def set_age(self, value):
if type(value) is int and 0 <= value:
self._age = value
else:
print("Not valid age")
age = property(get_age, set_age)- The setter checks that
ageis a non-negative integer. - The underscore prefix
_ageprevents recursive setter/getter calls.
Test the validation by creating instances with invalid ages:
fido = Dog("Fido", "Golden Retriever", 3, "05/22/2022")
clifford = Dog(
name="Clifford",
age=2,
breed="Big Red"
)
print(fido.age)
fido.birthday_celebration()
print(fido.age)
print(clifford.last_checkup)
clifford.checkup("03/02/2024")
print(clifford.last_checkup)
balto = Dog("Balto", "Husky", "Not an age")
steele = Dog("Steele", "Husky", -10)You should see the following output including error messages for invalid ages:
3
Fido is turning 4
4
None
Checking up with Clifford on 03/02/2024
03/02/2024
Not valid age
Not valid age
This concludes the technical lesson on creating a Dog class using Python OOP principles. Make sure to commit your changes and push to your GitHub repository following the Git workflow outlined above.