Last active
May 25, 2020 17:50
-
-
Save willy-r/a33d64f3bc50f76e5b0fbcd2416ac1eb to your computer and use it in GitHub Desktop.
Design a simplified version of Twitter, where users can post tweets, follow/unfollow others, and is able to see the 10 most recent tweets in the user’s news feed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User: | |
def __init__(self, user_name): | |
self.user_name = user_name | |
self.tweets = [] | |
self.follows = [] | |
def __str__(self): | |
return self.user_name | |
@property | |
def user_name(self): | |
return self._user_name | |
@user_name.setter | |
def user_name(self, name): | |
if not isinstance(name, str): | |
raise TypeError('Expected a string.') | |
self._user_name = name | |
def post_tweet(self, tweet): | |
self.tweets.insert(0, tweet) | |
def follow_user(self, user): | |
self.follows.append(user) | |
print(f'Now you’re following {user}.') | |
def unfollow_user(self, user): | |
if user not in self.follows: | |
print(f'You don’t follow {user}.') | |
self.follows.remove(user) | |
print(f'You unfollow {user}.') | |
def get_news_feed(self): | |
if not self.tweets: | |
print('This user hasn’t tweeted anything yet.') | |
# Returns ten or less tweets. | |
return self.tweets[:10] | |
def main(): | |
# Creates two users. | |
user_01 = User('William') | |
print(f'User {user_01} created.') | |
user_02 = User('Iago') | |
print(f'User {user_02} created.') | |
# Post some tweets with both users. | |
user_01.post_tweet('This is my first tweet!') | |
user_01.post_tweet('This is my second tweet!') | |
user_02.post_tweet('This is my first tweet ever!') | |
user_02.post_tweet('This is my second tweet ever!') | |
# One follows the other and one unfollows the other. | |
user_01.follow_user(user_02) | |
user_02.follow_user(user_01) | |
user_01.unfollow_user(user_02) | |
user_02.unfollow_user(user_01) | |
# Ten (or less) most recent tweets in both user's news feed. | |
print(f'\nMost recent tweets in {user_01}’s news feed:') | |
for tweet in user_01.get_news_feed(): | |
print(tweet) | |
print(f'\nMost recent tweets in {user_02}’s news feed:') | |
for tweet in user_02.get_news_feed(): | |
print(tweet) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment