Created
December 6, 2021 18:32
-
-
Save maddrum/0ceb2ed569eb6d860c6fc150e4183246 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
"""getters, setters and property decorators examples | |
Used to get and set protected variables(starts with _) | |
using property makes all code call getter and setter functions when rear and write do this class protected variable""" | |
class AddTesterToString: | |
def __init__(self, input_string): | |
self.input_string = input_string | |
# def getter function - gets _protected variable | |
def get_input_string(self): | |
print('getter') | |
return self._input | |
# setter function - sets value to _protected variable | |
def set_input_string(self, input_string): | |
print('setter') | |
self._input = input_string + ' tester' | |
# makes input string property - any code that gets value of input_string will use getter function, all that writes data will write to setter | |
input_string = property(get_input_string, set_input_string) | |
a = AddTesterToString('alala') | |
c = a.input_string | |
a.input_string = 'gala' | |
print(a.input_string) | |
# with property decorators - removes get_ and Set_ functions | |
class AssTesterToStringProperty: | |
def __init__(self, input_string): | |
self.input_string = input_string | |
@property # make setter | |
def input_string_a(self): | |
print('getter') | |
return self._input_string | |
@input_string_a.setter # decorattor for seter - name of protected variable, named as setter function | |
def input_string_b(self, value): | |
print('setter') | |
self._input_string = value + ' tester' | |
d = AddTesterToString('fala') | |
e = d.input_string | |
d.input_string = 'mala' | |
print(d.input_string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment