thclpr
thclpr

Reputation: 5938

Passing arguments to a function in Python

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?

Upvotes: 1

Views: 160

Answers (3)

TZHX
TZHX

Reputation: 5377

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 

Upvotes: 1

Blair
Blair

Reputation: 15788

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

Upvotes: 6

clyfish
clyfish

Reputation: 10450

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

Upvotes: 4

Related Questions