TypeError : takes 0 positional arguments but 1 was given

Viewed 23059

I have started learning Python. I have created a class which has a function and in that function i have a dictionary . No i am checking whether a key exists in the dictionary or not , after checking i am returning a value from the function .

Now i cam trying to access the function but when when i am doing so i am getting an error "TypeError: first_func() takes 0 positional arguments but 1 was given"

Below is the code which i am using :

class myFirst:
    def first_func():
        flag=0
        phonebook = {
            "A" : 938477566,
            "B" : 938377264,
            "C" : 947662781
        }
        # testing code
        if "A" in phonebook:
            flag=1
        if "D" not in phonebook:
            flag = 0
        return flag

myclassObj = myFirst()
status = myclassObj.first_func()

if status > 1:
    print ("Pass")
else:
    print ("fail")
3 Answers

methods (functions or procedures belonging to a class) require a self argument , you may be familiar with this from other languages, (unless explicitly defined as a @staticmethod but it doesn't look like that's what you're going for here) like so:

class myFirst:
    def first_func(self): # here
        flag=0
        phonebook = {
            "A" : 938477566,
            "B" : 938377264,
            "C" : 947662781
        }
        # testing code
        if "A" in phonebook:
            flag=1
        if "D" not in phonebook:
            flag = 0
        return flag

myclassObj = myFirst()
status = myclassObj.first_func()

if status > 1:
    print ("Pass")
else:
    print ("fail")

it should work with that minor change.

if you want to use the @staticmethod decorator (in case the function doesn't actually require information from the class instance) you would do this instead:

class myFirst:
    @staticmethod #here
    def first_func():

you can find out more by checking the doc here: https://docs.python.org/3/tutorial/classes.html

The error is you're not referencing self in your function signature. Change the signature to

def first_func(self):
    # rest of code

In addition to adding the self argument, you could consider shortening your code as well. Your function returns a boolean value which you assigned to status, and then you compared status to an int. Instead, you can do something like this to save a few lines-

myClassObj = myFirst()
if myClassObj.first_func():
    print "Pass"
else
    print "Fail"

The complexity gain is quite minimal, but there's no reason to assign the boolean value to another variable when you can just use the value that's returned by your function.

Related