-
Notifications
You must be signed in to change notification settings - Fork 0
/
User.py
92 lines (74 loc) · 2.74 KB
/
User.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from TextPost import TextPost
from ImagePost import ImagePost
from SalePost import SalePost
class User:
def __init__(self, username, password):
self.username = username
self.__password = password
self.__following = set()
self.__followers = set() # this is the observer list
self.is_online = True
self.__posts = []
self.notifications = []
def follow(self, user):
if user.is_online:
self.__following.add(user)
user.add_observer(self)
print(self.username + " started following " + user.username)
else:
print(user.username + " is not online")
def unfollow(self, user):
if user.is_online:
self.__following.remove(user)
user.remove_observer(self)
print(self.username + " unfollowed " + user.username)
else:
print(user.username + " is not online")
def add_observer(self, observer):
self.__followers.add(observer)
def remove_observer(self, observer):
self.__followers.remove(observer)
"""
here we use the observer pattern to notify the followers when a new post is published
"""
def notify_observers(self):
for observer in self.__followers:
observer.update(self.username + " has a new post")
def update(self, notification):
self.notifications.append(notification)
def publish_post(self, post_type, content, price=None, location=None):
if self.is_online:
post = create_post(self, post_type, content, price, location)
self.__posts.append(post)
print(post)
self.notify_observers()
return post
def print_notifications(self):
print(self.username + "'s notifications:")
for notification in self.notifications:
print(notification)
def log_out(self):
if self.is_online:
self.is_online = False
else:
print(self.username + " is already offline")
def __str__(self):
return "User name: " + self.username + ", Number of posts: " + str(
len(self.__posts)) + ", Number of followers: " + str(len(self.__followers))
def equal_password(self, password):
if password == self.__password:
return True
else:
return False
"""
here we use the factory pattern to create the different types of posts
"""
def create_post(owner, post_type, content=None, price=None, location=None):
if post_type == "Text":
return TextPost(owner, content)
elif post_type == "Image":
return ImagePost(owner, content)
elif post_type == "Sale":
return SalePost(owner, content, price, location)
else:
return None