user3014014
user3014014

Reputation: 819

Python -- Classes -- TypeError

I'm making a program that will do things with vectors. Right now i'm able to print out a vector, but i'm looking to be able to add to the vector if needed using my add function. However, it doesn't appear to work. It says that it can only take 1 argument, but two are given even though i am only entering one argument. Any advice?

class Vec:

def __init__(self, length = 0):
    self.vector = [0]*length

def __str__(self):
    return '[{}]'.format(', '.join(str(i) for i in self.vector))

def __len__(self):
    return len(self.vector)

def extd(self, newLen):
    self.vector.append([0]*newLen)
    return (', '.join(str(j) for j in self.vector))

Upvotes: 0

Views: 1250

Answers (2)

aIKid
aIKid

Reputation: 28252

You need to pass self as your first parameter there.

def add(self, newLen):

Otherwise, what would be passed is not newLen, but a pointer to the instance itself, hence the error.

By adding self, the first parameter that is automatically passed is the instance, and the second will be newLen.

See this console session, for example:

>>> class A:
    def pass_parameters(first_param, second_param=None):
        print(first_param, second_param)


>>> a = A()
>>> a.pass_parameters()
<__main__.A object at 0x000000000322BBE0> None
>>> a.pass_parameters('parameter')
<__main__.A object at 0x000000000322BBE0> parameter

Hope this helps!

Upvotes: 3

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

You're missing the self parameter for your add method. It should look like this:

def add(self, newLen):
    self.vector.append(newLen)
    return '[{}]'.format(', '.join(str(i) for i in self.vector))

In Python, when you call an instance method, the instance is automatically passed for you as the first parameter (usually named self).

Example:

v = Vec()
v.add(4)   # Essentially calls Vec.add(v, 4)

Upvotes: 2

Related Questions