2016-11-28 30 views
-3

有一天我在Python3中嘗試了一些簡單的練習,由於我在Python中很新,所以我對self概念有些疑惑。在Python中使用自我

下面是從HackerRank的30天的代碼挑戰中獲得的練習。 根據輸入的值,我必須評估一個人的年齡打印出型動物產出:

輸入(stdin)

4 
-1 
10 
16 
18 

代碼

class Person: 
    def __init__(self,initialAge): 
     # Add some more code to run some checks on initialAge 
     if initialAge < 0: 
      self.age = 0 
      print("Age is not valid, setting age to 0.") 
     else: 
      self.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.") 
     elif age >= 18: 
      print("You are old.") 

    def yearPasses(self): 
     # Increment the age of the person in here  
     global 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("") 

什麼我不知道是爲什麼def amIOld(self)部分,下面的代碼(使用的self.age代替age)不工作:

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 self.age >= 13 and self.age < 18: 
     print("You are a teenager.") 
    elif self.age >= 18: 
     print("You are old.") 

誰能這麼好心給我解釋的差異?

謝謝!

+3

可能是因爲你有'''selfage> = 13'''而不是''self.age> = 13''' – Lolgast

+0

對不起,我糾正了無意的錯字。但即使是現在它對代碼的其餘部分也沒有影響,因爲它並不像我期待的那樣工作。 – Lc0rE

回答

3

由於線

elif selfage >= 13 and self.age < 18: 

你有一個錯字的;在那裏應該是self.age,以訪問該類的age屬性。


在OOP中使用self屬性非常重要,因爲它是訪問和關於對象屬性的指導原則。用同樣的方法,你應該讓yearPasses方法:

def yearPasses(self): 
    self.age += 1 # increment the self attribute of age 

,而不是增加一個arbitary,外部,全局變量命名age

以人爲本 - 你不會只增加一個age;你增加這個人的年齡人,以後你會用這個年齡作其他用途。

+0

不經意間,錯字是轉錄的一個無意的錯誤。你用'self.age'指代的代碼並不像我在寫這篇文章之前所期待的那樣工作。 – Lc0rE

+1

看看我添加了關於'yearPasses'的內容。錯誤是從它派生的(當你在你的代碼中使用它時)。 – Uriel

+0

感謝您的評論。它現在如預期般運作良好。我確實在討論論壇上提供了一個指導,指出'全球時代'是解決這個問題的必須之路:/但我猜他們錯了 – Lc0rE

0

self用於表示類對象。例如,如果我們查看您的代碼。

人是一個類(類Person :),我們可以像一類提到任何名字作爲對象:

class Person: 
    def __init__(self,initialAge): 
     #your code 

person=Person(10) #or 
per=Person(20) #or 
per1=Person(5) #in your code class object has only one parameter rather than object(self). 

如果u要調用一個函數u應該這樣調用:

person.amIOld() #or 
per.amIOld() #here per is an object where we kept self as parameter in that function. 

但是有一點你必須記住自己應該是​​任何函數中的第一個參數,因爲編譯器認爲函數中的第一個參數是object(self)的表示。

如果您想要進一步澄清,請發送郵件給我[email protected]