Search code examples
pythonpython-decoratorsclass-method

how to use reduce the multiple set / unset function of each indivdual elemnt


How can i make this code more compact considering i will have multiple values to assign and unassign

class A:
    def __init__(self,*args,**kwargs):
        self._a = 0
        self._b =0
    def set_a(self):
        self._a = 1
    def set_b(self):
        self._b = 1
    def unset_a(self):
        self._a =0
    def unset_b(self):
        self._b = 0

x=A()
x.set_a() 
print(x._a) # 1
x.unset_a()
print(x._a) # 0

i just want to avoid to write multiple set and unset function, just a simple 1 function where i pass the type (set/unset) and which varibale to target , that will do it


Solution

  • You could use setattr based on a pre defined config to make it more compact

    class A:
        _a = 0
        _b = 0
    
        var_config = {
            '_a': {'unset': 0, 'set': 1}, 
            '_b': {'unset': 0, 'set': 1}, 
        }
    
        def set_var(self, var, action='set'):
            setattr(self, var, self.var_config[var][action])
    
    
    >>> x = A()
    >>> print(x._a)
    0
    
    >>> x.set_var('_a') 
    >>> print(x._a)
    1
    
    >>> x.set_var('_a', action='unset') 
    >>> print(x._a)
    0