TypeError: testFunction() missing 1 required positional argument: 's'

Question:

I see similar questions asked but in the simple scenario I am trying to understand what I am missing

class test:
    def testFunction(self,s:str):
        return s

print (test.testFunction("test"))

I keep getting

TypeError: testFunction() missing 1 required positional argument: ‘s’

Asked By: Mike Curtis

||

Answers:

You first need to instantiate an object of the class test.

class test:
    def testFunction(self,s):
        return s

test_obj = test()
print (test_obj.testFunction("test"))

Or, if you have no need to reuse the object, you can do the more concise

class test:
    def testFunction(self,s):
        return s

print (test().testFunction("test"))

But if the object isn’t reused, you may have no need to define a class at all. The above is more or less the same as running:

def testFunction(s):
     return s
    
print (testFunction("test"))
Answered By: Josh Bone

The above answer already mentions some "official" ways. Still if you want to directly fix the "TypeError: testFunction() missing 1 required positional argument: ‘s’". You just need to add a argument which is self (test class) like below:

class test:
    def testFunction(self,s:str):
        return s

print(test.testFunction(test, "x")) # x
print(test.testFunction) # <function test.testFunction at 0x0000018C3ADBE160>
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.