I have written below code to create/get a dict with n number of key, value pairs. Main idea is to use the same instantiated class object across my code and play around with k/v pairs.
class DataForm: def __init__(self): self.data_dict = dict() def create_key_value_pair(self, key, value): self.data_dict[key] = value def get_dict(self): return self.data_dict ob1 = DataForm() ob1.create_key_value_pair("Jon", 28) ob1.get_dict()
I was trying to understand and implement the above work(with some data validation) using getter/setter in Python.
class DataFormNew: def __init__(self): self._curr_dict = dict() @property def curr_dict(self): return self._curr_dict @curr_dict.setter def curr_dict(self, args): key, val = args if 0 < val < 100: self._curr_dict[key] = val else: raise ValueError("Value is not in range") ob2 = DataFormNew() ob2.curr_dict ob2.curr_dict = ('Jack', 10)
Few points on which I would need clarification?
- Which approach is better?
- Am I trying to complicate a simple job by using python @property (getter/setter) ?
- In which scenario we should choose to implement our class with getter/setter?
PS: Actually it's not just about dict creation. I'm running my code on AWS EC2 server where for every task, there can be n number of files to read and write them in DB. For every file, there is going to be unique id which i'm storing in dict dynamically. Each of (filename, unique id) creates a key,value pair. Later, I have queries to update DB based on this unique id against every file. I'm using object oriented approach to simplify the task.