Search code examples
pythonstatic-methods

How to access python static method which contain instance members?


I try to learn static methods in python. Here is my code-

class ABC:
    def __init__(self):
        self.a = 10
        self.b = 20
        self.lst = []

    @staticmethod
    def addNappend(self, c):
        sum = self.a + self.b + c
        self.lst.append(sum)
        print(self.lst)

if __name__ == '__main__':
    ABC.addNappend(30)

I am getting error to run my code. [TypeError: addNappend() missing 1 required positional argument: 'c']

What need to changes? Thanks all of u.


Solution

  • The message is clear: the method requires two arguments: an ABC object and another value; these are positional arguments. Since you called this as a class method, rather than an instance method, you have to explicitly provide the ABC object. At the moment, you have no self to alter; what did you expect that call to do?

    Instead, instantiate an object and use that:

    phone_button = ABC()
    phone_button.addNappend(30)
    

    Note that this is not at all related to making this a static method ... which seems to serve no purpose in this class.