Is there a way I can create a class with varied number of attributes and create corresponding getters and setters for these attributes?
My sample code is shown below.
class A:
def __init__(self, **options):
self._options = options
for key, value in options.items():
setattr(self, f"_{key.lower()}", value)
setattr(self, f"get_{key.lower()}", lambda : getattr(self, f"_{key.lower()}", None))
a = A(dimension = 2, name = "Unknown Alphabet")
for key, value in a.__dict__.items():
print(f"A[{key.lower()}] = {value}")
print(a.get_name())
print(a.get_dimension())
new_santa_clause = A(location = "North Pole", vehicle = "Teleportation", naughty_kids_list = [])
for key, value in new_santa_clause.__dict__.items():
print(f"SantaClause[{key}] = {value}")
print(new_santa_clause.get_location())
print(new_santa_clause.get_vehicle())
print(new_santa_clause.get_naughty_kids_list())
Output of execution is shown below
A[_options] = {'dimension': 2, 'name': 'Unknown Alphabet'}
A[_dimension] = 2
A[get_dimension] = <function A.__init__.<locals>.<lambda> at 0x000002334B4EC678>
A[_name] = Unknown Alphabet
A[get_name] = <function A.__init__.<locals>.<lambda> at 0x000002334B4EC1F8>
Unknown Alphabet
Unknown Alphabet
SantaClause[_options] = {'location': 'North Pole', 'vehicle': 'Teleportation', 'naughty_kids_list': []}
SantaClause[_location] = North Pole
SantaClause[get_location] = <function A.__init__.<locals>.<lambda> at 0x000002334B4ECA68>
SantaClause[_vehicle] = Teleportation
SantaClause[get_vehicle] = <function A.__init__.<locals>.<lambda> at 0x000002334B4EC438>
SantaClause[_naughty_kids_list] = []
SantaClause[get_naughty_kids_list] = <function A.__init__.<locals>.<lambda> at 0x000002334B4ECCA8>
[]
[]
[]
The values are getting set properly and getters are also getting created properly. Its just that when the getters are executed, proper values are not returned.