Reputation: 1721
I got the following python code where printSaved
is called when a button is clicked (using the wx library and python 2.7.2). But when this happens i got a really strange error
Traceback (most recent call last):
File "./program.py", line 135, in printSaved
s = self.readSaved()
TypeError: readSaved() takes no arguments (1 given)
Here is the code
def readSaved():
f = codecs.open((os.getenv('HOME') +'/Dokument/savefile.txt') ,'r','utf-8')
l = f.readlines()
f.close()
return l
def printSaved(self,event):
s = self.readSaved()
for l in s:
print l
I fixed the problem by adding one argument to readSaved(somethingUseless)
and everything worked fine. My question is what is passed to readSaved and HOW/WHY? Does this have something to do with the event?
Upvotes: 1
Views: 92
Reputation: 3898
Is it defined within a class? I suppose it does, since the second method takes self
.
If readSaved
is an instance method, it takes self
as first parameter as well. If you don't need it, use the @staticmethod
decorator instead:
@staticmethod
def readSaved():
f = codecs.open((os.getenv('HOME') +'/Dokument/savefile.txt') ,'r','utf-8')
l = f.readlines()
f.close()
return l
Upvotes: 1
Reputation: 81724
As it is a method -- you're calling it as a method, anyway -- you have to have at least self
as an argument. When a function is called as a method, the object you call the method through is passed as the first argument to that function.
Upvotes: 0
Reputation: 46233
In Python, the object on which a method is called is always passed in explicitly as an argument. This argument is conventionally called self
.
The correct definition for readSaved()
as an instance method should have this as the first line:
def readSaved(self):
# ...
If you want it to be a module-level function, you should call it as follows:
s = readSaved()
Upvotes: 3
Reputation: 799460
Methods are passed the instance as the first argument.
Upvotes: 2