Created
February 22, 2023 10:57
-
-
Save fbidu/5a148e31534f8e8763fe2a5848fc0eca to your computer and use it in GitHub Desktop.
simple snippet for a read-only wrapper around a base class
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: | |
""" | |
User class | |
It has some methods and properties to simulate the functions | |
of a regular class. | |
""" | |
def __init__(self, first_name, last_name, email, password): | |
self.first_name = first_name | |
self.last_name = last_name | |
self.email = email | |
self.password = password | |
def reversed_email(self): | |
return self.email[::-1] | |
def __str__(self): | |
return f"User: {self.email}" | |
@property | |
def full_name(self): | |
return f"{self.first_name} {self.last_name}" | |
@full_name.setter | |
def full_name(self, value): | |
self.first_name, self.last_name = value.split(" ") | |
class ReadOnlyUser: | |
def __init__(self, *args, **kwargs): | |
self._user = User(*args, **kwargs) | |
def __getattr__(self, name): | |
return getattr(self._user, name) | |
def __setattr__(self, name, value): | |
if name == "_user": | |
super().__setattr__(name, value) | |
else: | |
raise RuntimeError("This instance is read-only.") | |
reg_user_1 = User("Joseph", "Test", "[email protected]", "123456") | |
fixtured_user = ReadOnlyUser("Fixed", "Test!", "[email protected]", "123456") | |
reg_user_2 = User("James", "Test", "[email protected]", "123456") | |
print("Reading initial values:") | |
print(reg_user_1.email) | |
print(fixtured_user.email) | |
print(reg_user_2.email) | |
print(" ") | |
print("Changing values:") | |
reg_user_1.email = "[email protected]" | |
reg_user_2.email = "[email protected]" | |
try: | |
fixtured_user.email = "should not work" | |
except RuntimeError: | |
print("Correctly raised RuntimeError!") | |
else: | |
print("Should not be printed!") | |
print(" ") | |
print("Reading values after changes:") | |
print(reg_user_1.email) | |
print(fixtured_user.email) | |
print(reg_user_2.email) | |
print(" ") | |
print("Changing values with setters...") | |
reg_user_1.full_name = "New Name" | |
try: | |
fixtured_user.full_name = "New Name" | |
except RuntimeError: | |
print("Correctly raised RuntimeError!") | |
else: | |
print("Should not be printed!") | |
reg_user_2.full_name = "New Name 2" | |
print(" ") | |
print("Reading values after changes:") | |
print(reg_user_1.full_name) | |
print(fixtured_user.full_name) | |
print(reg_user_2.full_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment