Search code examples
pythonstatic-methods

Modify variables with a static method


I know static methods should be kept to a minimum and the whole idea of static methods is that they don't interact with the class but is there a way to do it?

Requirements:

class System with 2 attributes - divisible and obvisible, which are empty lists

static method register_divisible(name) takes parameter name and appends it to divisible

Example:

class System:
    def __init__(self):
        self.divisible = []
        self.obvisible = []

    @staticmethod
    def register_divisible(name):
        self._divisible.append(name)

Solution

  • For this requirement, you have to define divisible and obvisible outside of the constructor and refer variable with class name instead of self

    class System:
        divisible = []
        obvisible = []
    
        @staticmethod
        def register_divisible(name):
            System.divisible.append(name)
    
    #Instance        
    a=System()
    a.register_divisible('one')
    
    #Static
    System.register_divisible("two")
    
    print(a.divisible) #prints ['one','two']
    print(System.divisible) #prints ['one','two']