Design Pattern Examples
Overview of object-oriented design patterns
mediator_user_classes.py
Go to the documentation of this file.
8
9
10class User:
11
12
14
15
16 @property
17 def Name(self) -> str:
18 return self._name
19
20
21
22
26 def __init__(self, name = "") -> None:
27 self._name = name
28
29
31
32
33
44 def __eq__(self, o) -> bool:
45 if isinstance(o, User):
46 return self._name == o._name
47 elif isinstance(o, str):
48 return self._name == o
49 else:
50 raise TypeError("Expecting a User type or string to compare to.")
51
52
53
55
56
57
61
62
64
65
70 @property
71 def UserNames(self) -> list[str]:
72 userNames = []
73
74 for user in self._users:
75 userNames.append(user.Name)
76
77 # Case-insensitive sort
78 userNames.sort(key=str.lower)
79 return userNames
80
81
82
83
84 def __init__(self) -> None:
85 self._users = [] # type: list[User]
86
87
91
92
93
101 def _SearchForUser(self, name : str) -> int:
102 foundIndex = -1
103 try:
104 foundIndex = self._users.index(User(name))
105 except ValueError:
106 # name was not found in the list
107 pass
108 return foundIndex
109
110
117 def FindUser(self, name : str) -> User:
118 foundIndex = self._SearchForUser(name)
119 if foundIndex != -1:
120 return self._users[foundIndex]
121 return None
122
123
124
132 def AddUser(self, name : str) -> None:
133 if not name:
134 raise ValueError("Must specify a user name to add it to the user list.")
135
136 if not self.FindUser(name):
137 self._users.append(User(name))
138
139
140
145 def RemoveUser(self, name : str) -> None:
146 foundIndex = self._SearchForUser(name)
147 if foundIndex != -1:
148 self._users.remove(User(name))
str Name(self)
Property getter for the name of the user: value = o.Name
bool __eq__(self, o)
Determine if the name or the specified User matches this User's name.
list[str] UserNames(self)
Property getter for the user names contained in this list: value = o.UserNames The list is always sor...
None AddUser(self, str name)
Add the specified user name as a user.
User FindUser(self, str name)
Retrieve the User instance for the specified user name.
None RemoveUser(self, str name)
Remove the specified user name as a user.
int _SearchForUser(self, str name)
Get an iterator pointing to the user with the specified name.
_users
List of User instances representing all known users.