我正在迈出 Python 编程的第一步,我有一个名为 node
的类,它包含一个名为 的
。我试图创建一个返回列表长度的函数,但它失败了。这是我的代码:node
列表(我认为这是合法的) >儿子
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
显然我误解了什么,但是什么?
最佳答案
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()
关于python - 在python中的类中定义一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631991/