For the sake of discussion, lets say I want to write and read values from a dictionary
but I want to append some string to the dictionary key. Instead of having the user do the string manipulation, I want to hide it inside setter
and getter
methods. This works no problem with the Python setter
method since I can send a list full of information that can be parsed. It does NOT, however, work with the getter
method since arguments cannot be sent to getter
. I have concocted the workaround shown below where the getter
returns a function which accepts the arguments and does what I want. I'm just wondering if this acceptable Python or if I will regret using this approach.
class tester(object):
def __init__(self):
self._dict = {}
def _set(self,some_list):
self._dict.update({some_list[0]+'_'+some_list[1]: some_list[2]})
def _get(self):
return self._func
def _func(self,key1,key2):
keys = key1+'_'+key2
return self._dict[keys]
props = property(_get, _set)
a = tester()
value = [1,2,3,4,5]
a.props = ('main_key','sub_key',value)
print(a.props('main_key','sub_key'))
I have searched high and low for ways to use setter
and getter
that suit my needs, but all I see are people asserting that Python doesn't need them and we should all just be adults and access the attributes directly. The closest I've found is this question, but I find my solution more direct.