2016-09-04 48 views
-1
class Person: 
    #age = 0 
    def __init__(self,initialAge): 
     # Add some more code to run some checks on initialAge 
     if(initialAge < 0): 
      print("Age is not valid, setting age to 0.") 
      age = 0 
     age = initialAge 

    def amIOld(self): 
     # Do some computations in here and print out the correct statement to the console 
     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): 
     # Increment the age of the person in here 
     Person.age += 1 # I am having trouble with this method 

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("") 
  • yearPasses()應該增加age由1,但現在它不會做任何事情時調用

  • 我如何適應它使其工作?

+0

@ PM2Ring實際上,我是新來的對象編程...甚至不知道如何描述我的問題(跑開 –

+0

OOP開始有點奇怪,但像編程中的任何東西,有足夠的練習,它很快就會成爲熟悉的人 –

回答

1

您需要age作爲Person類的實例屬性。要做到這一點,您可以使用self.age語法,就像這樣:

class Person: 
    def __init__(self, initialAge): 
     # Add some more code to run some checks on initialAge 
     if initialAge < 0: 
      print("Age is not valid, setting age to 0.") 
      self.age = 0 
     self.age = initialAge 

    def amIOld(self): 
     # Do some computations in here and print out the correct statement to the console 
     if self.age < 13: 
      print("You are young.") 
     elif 13 <= self.age <= 19: 
      print("You are a teenager.") 
     else: 
      print("You are old.") 

    def yearPasses(self): 
     # Increment the age of the person in here 
     self.age += 1 

#test 

age = 12 
p = Person(age) 

for j in range(9): 
    print(j, p.age) 
    p.amIOld() 
    p.yearPasses()  

輸出

0 12 
You are young. 
1 13 
You are a teenager. 
2 14 
You are a teenager. 
3 15 
You are a teenager. 
4 16 
You are a teenager. 
5 17 
You are a teenager. 
6 18 
You are a teenager. 
7 19 
You are a teenager. 
8 20 
You are old. 

你原來的代碼有之類的語句

age = initialAge 

在它的方法。這只是在該方法中創建一個名爲age的本地對象。這些對象不存在於方法外部,並且在方法終止時被清除,因此下次您調用該方法時,其舊值age已丟失。

self.age是類實例的一個屬性。該類的任何方法都可以使用self.age語法訪問和修改該屬性,並且該類的每個實例都有其自己的屬性,因此在創建Person類的多個實例時,每個實例都將擁有自己的.age

也可以創建屬於類自身的屬性的對象。這允許該類的所有實例共享一個對象。例如,

Person.count = 0 

創建Person類的名爲.count的類屬性。您還可以通過在方法外部放置賦值語句來創建類屬性。例如,

class Person: 
    count = 0 
    def __init__(self, initialAge): 
     Person.count += 1 
     # Add some more code to run some checks on initialAge 
     #Etc 

將跟蹤您的程序迄今創建了多少個Person實例。

+0

謝謝!那正是我被困在的地方......我不知道如何在所有情況下使用相同的「年齡」變量以及「自我」如何工作 –

+0

好的,謝謝。面向對象的基礎知識 –

+0

@ jm33_m0希望我添加的新信息使事情變得更清晰。 –