Created
July 8, 2023 12:09
-
-
Save Abdurahman-hassan/2f5229e475b0689852ba7fecfb8c11fc to your computer and use it in GitHub Desktop.
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
# Encapsulation | |
def encapsulated_function(some_value): | |
class HiddenClass: | |
def __init__(self, value): | |
self.value = value | |
def display_value(self): | |
print(self.value) | |
instance = HiddenClass(some_value) | |
instance.display_value() | |
encapsulated_function(5) # Will print 5 | |
# Dynamic Class Creation | |
def create_dynamic_class(attributes): | |
class DynamicClass: | |
def __init__(self, **kwargs): | |
for attr, value in kwargs.items(): | |
setattr(self, attr, value) | |
return DynamicClass(**attributes) | |
dynamic_instance = create_dynamic_class({'name': 'John', 'age': 30, 'country': 'USA'}) | |
print(dynamic_instance.name) # John | |
print(dynamic_instance.age) # 30 | |
print(dynamic_instance.country) # USA | |
# Use in Decorators or Factories | |
def factory_function(is_advanced=False): | |
class BasicCalculator: | |
def calculate(self, x, y): | |
return x + y | |
class AdvancedCalculator(BasicCalculator): | |
def calculate(self, x, y): | |
return x * y | |
return AdvancedCalculator() if is_advanced else BasicCalculator() | |
calculator = factory_function(is_advanced=True) | |
print(calculator.calculate(5, 4)) # 20 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment