开发者

Python 3.1.1 Class Question

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


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')


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

mydata = Data()
mydata.add('yes')


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜