defining a method inside a class in python
我将在python编程中迈出第一步,我有一个名为
1 2 3 4 5 6 7 8 9 | class node: name="temp" ID=-1 abstract="a short description" text="the full description" sons=[] def sLen(none): print ("hello") return len(self.sons) |
下面是错误:
NameError: global name 'self' is not defined
如果我试图移除自我:
NameError: global name 'self' is not defined
很明显我误解了什么,但是什么?
型
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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() |
号
型
类方法的第一个参数始终是对"self"的引用。
也许你也会在这里找到有趣的答案:自我的目的是什么?.
引用最重要的位:
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.
号
如果您想更深入地讨论Python中的类定义,当然,官方文档是从http://docs.python.org/tutorial/classes.html开始的。
型
您调用了方法
1 | return len(none.sons) |