Polishing and Refactoring
Learn how to refactor and improve Chirpy.
Chirpy has come a long way—users can now create posts, like content, comment, and even have verified accounts. However, as our platform expands, we must ensure our code structure evolves as well.
Fixing private data members
Recall our lesson on “Encapsulation and Private Data Members,” where we learned that each private data member within a class should start with a leading underscore (_
). While this convention doesn’t strictly prevent access in Python, it clearly communicates to other developers that these attributes aren’t intended for direct use. More importantly, this practice supports the principle of abstraction, which involves hiding internal implementation details and exposing only essential functionalities to the outside world.
Did you know?
By convention, all data members of a class should be treated as private.
Earlier, we applied this approach only to the password attribute. Now, it’s time to consistently adopt this convention across all data members in our Chirpy project. Let’s get started and refactor our code!
from user import User from post import Post class VerifiedUser(User): def __init__(self, username, display_name, password): # Inherit attributes from User super().__init__(username, display_name, password) # Mark the user as verified self.verification_badge = True def get_verification_status(self): return "Verified ✅" if self.verification_badge else "Regular" # Overriding create_post() to add a "✅ " prefix to the content def create_post(self, content): # Add a special flair to posts created by verified users verified_content = "✅ "+ content post = Post(verified_content, self) self._posts.append(post) return post
Now, all the private attributes have been ...