I'm trying to build a class in python in which variable assignment and retrieval need to be done through a different class with its logic for set_value and get_value.
MyObj class gives the logic for set_value and get_value
Class MyObj:
def __init__(self):
self.value = 0
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
The user creates a MyClass object and sets/gets values to these variables, but the MyObj class will be 100% abstracted from the user.
class MyClass:
item1 = MyObj()
item2 = MyObj()
item3 = MyObj()
def __setattr__(self, key, value):
print(f"set logic :: {key}, {value}")
# key.set_value(value)
def __getattribute__(self, item):
print(f"get logic :: {item}")
# return item.get_value()
Myclass will behave like any other python class but with setter and getter logic coming from MyObj.
cls = MyClass()
cls.item1 = 10 # Issue: this should not replace variable value from class object.
print(cls.item1) # Issue: this should not return class object
Issue:
- Currently, this will be done through the
__setattr__
and__getattribute__
methods, but I can't get the code working as the parameters are in the string. - I don't want to manually type getter and setter for each variable in MyClass.
- User should be able to read and write variables of MyClass like standard python class variables.
- https://github.com/ramazanpolat/prodict this lib does something similar but not what I am looking for.