1

I'm not sure why I'm getting the message error

TypeError: __init__() takes exactly 3 arguments (4 given)

for the code described below:

class Worker(object):
    def __init__(arg1,arg2,arg3):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3
    def some_function(self):
        print "it works: " + arg1 + arg2 + arg3

w=Worker("a","b","c")
w.some_function()

What could I be missing?

3 Answers 3

6

It should be def __init__(self, arg1,arg2,arg3):. You'll also need to change the print statement in some_function to

print "it works: " + self.arg1 + self.arg2 + self.arg3
Sign up to request clarification or add additional context in comments.

Comments

4
def __init__(self,arg1,arg2,arg3):

2 Comments

after updating with your sugestion, im having: NameError: global name 'arg1' is not defined. should i set global arg1, arg2 , arg3 ?
Ah, thanks, i figured that out after writing the comentary. thanks for that :)
1

The first argument expected for any class function should always be self.

Well, the name is unimportant, but that's the meaning of it.

So your function definintion should look like:

def __init__(self,arg1,arg2,arg3): 
    self.arg1 = arg1 
    self.arg2 = arg2 
    self.arg3 = arg3 

6 Comments

This is only true for the methods of instances of a class. Not if you use the methods directly on the class: Worker.some_function(self) is equivalent to w.some_function()
@MarkusUnterwaditzer so the function shouldn't be defined as def __init__(self, arg1, arg2, arg3)??
They should. I'm just saying because you said it's true for all methods. There are also classmethods that don't take the self argument.
@MarkusUnterwaditzer class method is a confusing term also. Since there is a @classmethod decorator that passes the class as the first argument.
@rantanplan I just call them methods (the ones that take self as first arg) and class-methods (the ones using the @classmethod decorator).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.