tags:

views:

62

answers:

4

I'm a new Python programmer who is having a little trouble using 'self' in classes. For example:

class data:
    def __init__(self):
        self.table = []
    def add(self, file):
        self.table.append(file)
data.add('yes')

In this function I want to have table be a variable stored in the class data and use add to modify it. However, when I run this script it gives me the error:

Traceback (most recent call last):
  File "/Projects/Python/sfdfs.py", line 7, in <module>
    data.add('yes')
TypeError: add() takes exactly 2 positional arguments (1 given)

I assume that I am trying to call the function the wrong way in this instance, as this syntax is very similar to an example in the python documentation: http://docs.python.org/3.1/tutorial/classes.html

+8  A: 

You first need to make an instance of the class:

mydata = data()

then you can call the method -- on the instance, of course, not on the class:

mydata.add('yes')
Alex Martelli
+2  A: 

You need to instantiate the class before you can call methods on it:

mydata = Data()
mydata.add('yes')
Ignacio Vazquez-Abrams
+1  A: 

You are trying to call data.add() somewhat like you would call a static method in Java. Try doing this instead:

d = data()
d.add('yes')

The self parameter tells the method that it operates on an object of type data.

inspectorG4dget
+2  A: 

you are calling the add method on the class object not an instance of the class.

It looks like what you want to do is:

classInst = data() #make an instance

classInst.add("stuff") #call the method

When add is invoked on an instance object, the instance object is passed as the self argument to the method. Having the self argument differentiates class methods from instance methods.

Anatoly Fayngelerin