1

I am creating a Python class, that will include a method that ideally takes a list as an input. The method is supposed to take one of the member values, and determine a bin value, based on a sorted input list.

class sdata:  
    def __init__(self, score, sidx=-1):
        self.score = score
        self.sidx = sidx
        
    def getsidx(sblist):
        self.sidx = 0
        for s in sblist:
            if self.score < s:
                return
            self.sidx += 1
        return

But when I try to run it, i.e...

a = sdata(0.33)
a.getsidx([0.50, 0.75])

...I get an error message of TypeError: getsidx() takes 1 positional argument but 2 were given

How do I tell Python to treat the input to a class method as a arbitrary-length list, and not try to use the first argument of the list as the sole input value?

1 Answers1

2

The problem is that your method getsidx is not a static method (very brielfy put; static methods are called uppon the class, not a particular object of the class, that is, they do not have the parameter "self").

You have 2 options;

1.) Add parameter self to your getsidx method. Just change it to:

def getsidx(self, sblist):

The body of the function remains unchanged. This is what most class methods look like in Python. The object uppon which the method is called is always the first parameter passed to the method. A convention is to name it self.

2.) Change the logic of your method to not require the parameter self, and make this method a static method of your class (this requires more changes and I suppose the 1st solution is the more desired one). For more info on static methods: Static methods in Python?

waykiki
  • 914
  • 2
  • 9
  • 19
  • Thanx, option #1 instantly fixed things. Obviously, I am new to using Python classes. Are there useful situations, when that 1st argument is something other than `self`? – NaiveBayesian Oct 27 '20 at 13:19
  • @NaiveBayesian whenever you don't mark a method as static, then regardless of how you name the 1st argument, it will be the object itself. You could write def getsidx(somethingCool, arg2, arg3, ...) and somethingCool would be the object itself. It's just a convention to name the first argument "self", because it always will be the object itself. Only when using the keyword static, does the 1st argument not become the object, but the actual 1st argument passed. You should use static methods whenever the method doesn't require the object, but only the class itself. Can't fit more info in the com – waykiki Oct 28 '20 at 16:15