From 7be161c161f88cbefe86861c2c0fa283f25f0042 Mon Sep 17 00:00:00 2001 From: Rotem Albukrek <95996826+RotRotAl@users.noreply.github.com> Date: Wed, 7 Aug 2024 15:27:49 +0300 Subject: [PATCH] refactor(encapsulation-3.py): Add encapsulation and applies srp the example wasn't following single responsibility principle by mixing i/o operation with setter/getter. and the increment function volute the encapsulation of the setter. --- 06.Encapsulation/encapsulation-3.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/06.Encapsulation/encapsulation-3.py b/06.Encapsulation/encapsulation-3.py index 08a447a..0a97ae1 100644 --- a/06.Encapsulation/encapsulation-3.py +++ b/06.Encapsulation/encapsulation-3.py @@ -27,31 +27,33 @@ def set_val(self, val): self.val = val def get_val(self): - print(self.val) + return self.val def increment_val(self): - self.val = self.val + 1 - print(self.val) + self.set_val(self.get_val()+1) a = MyInteger() a.set_val(10) -a.get_val() +print(a.get_val()) a.increment_val() +print(a.get_val()) print("Before Break") # Trying to break encapsulation in a new instance with an int c = MyInteger() c.val = 15 -c.get_val() +print(c.get_val()) c.increment_val() +print(c.get_val()) print("After Break") # Trying to break encapsulation in a new instance with a str b = MyInteger() b.val = "MyString" # <== Breaking encapsulation, works fine -b.get_val() # <== Prints the val set by breaking encap +print(b.get_val()) # <== Prints the val set by breaking encap b.increment_val() # This will fail, since str + int wont work +print(b.get_val()) print("Changing DataType") ''' O/P- @@ -65,4 +67,4 @@ def increment_val(self): Traceback (most recent call last): self.val = self.val + 1 TypeError: can only concatenate str (not "int") to str -''' \ No newline at end of file +'''
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: