2011-07-30 105 views
0
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 

現在,在這一點上,它說,沒有找到自己的名字。如果我只嘗試getval()(沒有自身前綴),那麼它表示沒有getval方法需要0個參數。請任何人都可以解釋我爲什麼這個代碼不起作用?這段代碼爲什麼不起作用? (蟒蛇)

+0

請重新格式化您的帖子。 – agibalov

回答

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() 
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 

Read the Python tutorial

+3

我可能會注意到'MyClass.val'和'x.val'是不同的變量。 – robert

相關問題