Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing self as an argument in a helper method

I am working with a class and am trying to call a helper method from within the class. I got the following code to work, but I am unsure why I have to pass "self" as an argument to the helper function when I call it when I already have "self" as an argument in the method. Is there a reason that I have to pass it as an argument when I call Frequency.__helper(self, record) in the example below?

Thanks!

class Frequency:

    def __init__(self, record):
        self.record = record

    def __helper(self, datalist)
        do something to datalist...

    def getFreq(self):
        allrec = self.record
        record = allrec[1].split(' ')
        var = Frequency.__helper(self, record)
        return var
like image 403
Lance Collins Avatar asked Jan 11 '12 03:01

Lance Collins


2 Answers

The right way to call the method is just

var = self.__helper(record)

That does the same thing, but in a more intuitive fashion.

like image 191
David Robinson Avatar answered Sep 24 '22 01:09

David Robinson


Yes, in this case you have to, because you're not declaring the function as an @staticmethod. When a method is not static, it requires an instance to be passed.

If you do something like:

class Frequency:
    @staticmethod
    def test(datalist):
        pass

you'll not be required to define self into the argument list.

like image 25
Gonzalo Larralde Avatar answered Sep 22 '22 01:09

Gonzalo Larralde