Search code examples
pythonfunctionpython-3.xself

How to pass arguments to python function whose first parameter is self?


Take the following simplified example.

class A(object):
    variable_A = 1
    variable_B = 2

    def functionA(self, param):
        print(param+self.variable_A)

print(A.functionA(3))

In the above example, I get the following error

Traceback (most recent call last):
  File "python", line 8, in <module>
TypeError: functionA() missing 1 required positional argument: 'param'

But, if I remove the self, in the function declaration, I am not able to access the variables variable_A and variable_B in the class, and I get the following error

Traceback (most recent call last):
  File "python", line 8, in <module>
  File "python", line 6, in functionA
NameError: name 'self' is not defined

So, how do I access the class variables and not get the param error here? I am using Python 3 FYI.


Solution

  • You must first create an instance of the class A

    class A(object):
        variable_A = 1
        variable_B = 2
    
        def functionA(self, param):
            return (param+self.variable_A)
    
    
    a = A()
    print(a.functionA(3))
    

    You can use staticmethod decorator if you don't want to use an instance. Static methods are a special case of methods. Sometimes, you'll write code that belongs to a class, but that doesn't use the object itself at all.

    class A(object):
        variable_A = 1
        variable_B = 2
    
        @staticmethod
        def functionA(param):
            return (param+A.variable_A)
    
    print(A.functionA(3))
    

    Another option is to use classmethod decorator. Class methods are methods that are not bound to an object, but to a class!

    class A(object):
        variable_A = 1
        variable_B = 2
    
        @classmethod
        def functionA(cls,param):
            return (param+cls.variable_A)
    
    print(A.functionA(3))