为什么这段代码不起作用?(蟒蛇)

Sha*_*kan 0 python methods class

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
Run Code Online (Sandbox Code Playgroud)

现在在这一点上它说没有找到名称self.如果我只尝试getval()(没有自己的前缀),那么它表示没有getval方法接受0个参数.请有人能解释一下为什么这段代码不起作用?

Joc*_*zel 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
Run Code Online (Sandbox Code Playgroud)

阅读Python教程.

  • 我可能会注意到`MyClass.val`和`x.val`是不同的变量. (3认同)