Reputation: 10685
I'm taking my first steps in python programming, I have a class named node
which holds a list of node
s (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?
Upvotes: 1
Views: 132
Reputation: 3572
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.
Upvotes: 1
Reputation: 7694
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()
Upvotes: 3
Reputation: 798616
You called the first argument to the method none
, not self
.
return len(none.sons)
Upvotes: 0