Hello,
I am currently working on my own project, and wanted to create a class that represents a bug.
I wrote the function .update_prority(new_priority) that updates the instance variable self.priority. It also checks if is withing a range of allowed priorities.
To do this check, I call the .update_priority function within the init() function.
After that worked, I thought why not assign all instance variables via the update function. That case, if I have checks later on they are automatically run later down the road.
This is my class so far:
class Bug:
instance_counter = 1
allowed_priorities = ["Low", "Middle", "High"]
def __init__(self, title="Title", description="Description", priority="Middle", category=None):
self.update_title(title)
self.update_description(description)
self.update_priority(priority)
self.id = Bug.instance_counter #assign a unique id to each the bug
Bug.instance_counter+=1
#update the title
def update_title(self, new_title):
self.title = new_title
def update_description(self, new_description):
self.description = new_description
# updates priority if the priority is in Tuple of allowed priorities
def update_priority(self, new_priority):
if new_priority in Bug.allowed_priorities:
self.priority = new_priority
else:
raise ValueError("Priority can only be Low, Middle or High")
def updated_category(self, new_category):
self.category = new_category
new_bug = Bug("Title 1", "Description", "Middle")
new_bug2 = Bug("Title 2", "Desc", "Low")
print(new_bug2.priority)
print(new_bug2.title)
print(new_bug2.id)
I added some execution code as an example as well.
My Question:
I know it is working, but is it allowed under style guidelines?
Can there be any issues down the road with this implementation?
One thing you could look into is separating the validation from the class itself, especially since you’re not certain what validation you actually need at this point. If you have a search around for OOP design patterns for validation you might find some nice ideas for this (there’s various options). The docs on Python descriptors might give you a few ideas too e.g. https://docs.python.org/3.10/howto/descriptor.html#complete-practical-example. This is a bit more complex than property but potentially offers a little more flexibility without directly altering the original class; worth a quick look anyway.
A lot of the OOP things take a long time to sink in (along with practice and use) but it sounds like you’re thinking about it the right way anyway which is definitely a good thing . I’m not sure codecademy introduces property in the course (perhaps briefly in one the advanced python topics) nor general design patterns so you might need to hunt elsewhere.
If you’re still new to using classes in general then I wouldn’t worry too much about them right now. They’re designed to make OOP development easier in the long term, I think getting used to classes and objects is a good idea and then you can worry about design patterns and so on.