Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 568
Parthapratim Neog Avatar asked Jan 30 '17 11:01

Parthapratim Neog


2 Answers

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))
like image 109
İzzet Altınel Avatar answered Nov 03 '22 11:11

İzzet Altınel


functionA in your snippet above is an instance method. You do not pass "self" directly to it. Instead, you need to create an instance in order to use it. The "self" argument of the function is, in fact, the instance it's called on. E.g.:

a = A()
a.functionA(3)

P.S. Note that your functionA calls print but doesn't return anything, meaning it implicitly returns None. You should either have it return a value and print it from the caller, or, as I have done above, call it and let it print on its own.

like image 20
Mureinik Avatar answered Nov 03 '22 11:11

Mureinik