2016-01-20 105 views
1

我最近開始學習python。並正在處理一個問題。分配之前引用的局部變量「age」

class Person: 
    age = 0 
    def __init__(self,initial_Age): 
     if initial_Age<0: 
      age=0 
      print("This person is not valid, setting age to 0.") 
     else: 
      age = initial_Age 

    def amIOld(self): 
     if(age<13): 
      print("You are young.") 
     elif(age>=13 and age<18): 
      print("You are a teenager.") 
     else: 
      print("You are old.") 
    def yearPasses(self): 
     age = age + 1 
T=int(input()) 
for i in range(0,T): 
age=int(input())   
p=Person(age) 
p.amIOld() 
for j in range(0,3): 
    p.yearPasses();   
p.amIOld(); 
print ("") 

我得到的錯誤顯示如下:

Traceback (most recent call last): 
File "solution.py", line 27, in <module> 
p.yearPasses();   
File "solution.py", line 19, in yearPasses 
age = age + 1 
UnboundLocalError: local variable 'age' referenced before assignment 

這種情況的輸入是這樣:

4(Number of test cases) 
-1 
10 
16 
18 

輸出必須是這樣的:

This person is not valid, setting age to 0. 
You are young. 
You are young. 

You are young. 
You are a teenager. 

You are a teenager. 
You are old. 

You are old. 
You are old. 

可以請你引導我w我做錯了什麼?由於

+0

阿里納斯(我想既然你是學習它可能是有用的):把更多的關注代碼風格,檢查[風格導(https://www.python.org/dev/peps/pep-0008/)。例如,使用'initial_age'而不是'initial_Age',使用駱駝式的方法名('am_i_old','year_passed'),不需要添加';'在行尾,不要使用像'T'和'p'這樣的短變量。 –

回答

5

在Python中,你必須使用明確self訪問實例屬性:

class Person: 
    def __init__(self, initial_Age): 
     if initial_Age < 0: 
      self.age = 0 
      print("This person is not valid, setting age to 0.") 
     else: 
      self.age = initial_Age 

    def amIOld(self): 
     if self.age<13: 
      print("You are young.") 
     elif self.age>=13 and self.age<18: 
      print("You are a teenager.") 
     else: 
      print("You are old.") 

    def yearPasses(self): 
     self.age += 1 
+0

太棒了。這工作。謝謝 – fahadkaleem

相關問題