strange problem with def in class

James Henderson james at logicalprogression.net
Wed Aug 18 02:56:40 CEST 2004


Johan wrote:
> I don't get it:
> I'm trying to write a "readfile" function which would replace some code from
> a __init__ function:
> 
> 1    import string
> 2    class landdict:
> 3        def __init__(self, file):
> 4                # Laadt de dictionnary van landen.
> 5                # Kijk in de actiefspel-file voor de file van waaruit je
> moet laden.
> 6                self.ld = {}
> 7                f = open(file, "r")
> 8                line = f.readline()
> 9                if line[0] == "#":
> 10                    line = f.readline()
> 11              while line != "":
> 12                    key = line[0:3]
> 13                    self.ld[key] = string.split(line[4:], ':')
> 14                    line = f.readline()
> 15              print self.ld
> 
> So I would like to replace the code from line 7 to line 14 with
> 
> readfile(filename)
> 
> while
> 
> def readfile(filename) is another function in the class
> 
> but I can't define this function.... when I call the function the
> interpreter throws an exception of unknown function
> what am I doing wrong?

Hi Johan

Other variables defined in a class are in a scope that cannot be 
accessed directly from within a method (Python newish nested scoping 
only works for functions inside functions).

Personally I would move your readline() function outside the class to 
the module level.

If you want to keep it in the class then either give it a self parameter 
or add "readline = staticmethod(readline)" after the definition of 
readline().  Then you can call it from within __init__() as 
self.readline(filename).

HTH,
James




More information about the Python-list mailing list