1

I'm taking my first steps in python programming, I have a class named node which holds a list of nodes (I think that legal) named sons. I tried to create a function that returns the length of the list but it fails. Here is my code:

class node:
    name="temp"
    ID=-1
    abstract="a short description"
    text="the full description"
    sons=[]
    def sLen(none):
        print ("hello")
        return len(self.sons)

and here is the error:

NameError: global name 'self' is not defined

if I try to remove the self:

NameError: global name 'self' is not defined

Clearly I have misunderstood something, but what?

Yotam
  • 10,295
  • 30
  • 88
  • 128

3 Answers3

3
class node:
    name="temp"
    ID=-1
    abstract="a short description"
    text="the full description"
    sons=[]
    def sLen(self): # here
        print ("hello")
        return len(self.sons)

n = node()
n.sons = [1, 2, 3]
print n.sLen()
Andrey Agibalov
  • 7,624
  • 8
  • 66
  • 111
  • Note that this only fixes one of the problems in the code though. – Ignacio Vazquez-Abrams Oct 03 '11 at 07:14
  • The only problem of this code is that I can't understand what it is supposed to do. From the view of Python, there are no problems. See my update, this code works fine. – Andrey Agibalov Oct 03 '11 at 07:17
  • @loki2302: The reason you can't understand the purpose of my code is that currently, it is mainly me toying around trying to figure stuff. If you are at all interested, I can tell you that I'm trying to build a simple RPG campaign manager. – Yotam Oct 03 '11 at 07:21
  • @Yotam: Well, you should probably consider using any existing solutions and not implementing all this stuff from scratch. In case you're writing RPG, concentrate on RPG and not on nodes. Unless "node" is a character ;-) – Andrey Agibalov Oct 03 '11 at 07:23
1

The first argument of a class method is always a reference to "self".

Possibly you will find interesting answers here too: What is the purpose of self?.

Quoting the most important bit:

Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on.

If you look for a more thorough discussion about classes definition in python, of course the official documentation is the place to start from: http://docs.python.org/tutorial/classes.html.

Community
  • 1
  • 1
Savino Sguera
  • 3,522
  • 21
  • 20
0

You called the first argument to the method none, not self.

return len(none.sons)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358