class MyClass:
def __init__(self):
pass
val = ""
def getval(self):
# code to get val
# ... and at the end:
self.val = "bla bla"
self.getval()
print val
现在在这一点上它说没有找到名称self。如果我只尝试getval()
(没有自己的前缀),那么它表示没有getval方法接受0个参数。请有人能解释一下为什么这段代码不起作用?
答案 0 :(得分:6)
这是一个更有意义的例子:
class MyClass:
def __init__(self):
pass
# this is a class variable
val = ""
def getval(self):
# code to get val
# ... and at the end:
self.val = "bla bla"
return self.val
# make a instance of the class
x = MyClass()
print x.getval()
# MyClass.val is a different class variable
print MyClass.val
答案 1 :(得分:1)
您尚未创建对象的实例。
class MyClass:
def __init__(self):
pass
val = ""
def getval(self):
# code to get val
# ... and at the end:
self.val = "bla bla"
self.getval()
print val
o = MyClass()
print o.getval()