2016-11-28 6 views
-3

先日私はPython3で簡単に演習をしようとしていましたが、私はPythonでかなり新しいので、selfのコンセプトに関する疑問があります。自己をPythonで使う

以下は、HackerRankの30日間のコードチャレンジから得た運動です。 入力の値に基づいて、私は貴様の出力をプリントアウトする1人の年齢を評価する必要があります。

入力(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)部分には、(代わりにageself.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.") 

誰かが私に違いを説明するのにとても親切にすることができます?

ありがとうございます!あなたがタイプミスをしているため、ライン

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

+3

'' 'self.age> = 13''ではなく' 'selfage> = 13'''を持っている可能性があります。 – Lolgast

+0

申し訳ありませんが、私は意図しないタイプミスを修正しました。しかし、今でも、私が期待していたように動作していないので、コードの残りの部分に影響はありません。 – Lc0rE

答えて

3

。そのクラスのage属性にアクセスするには、その上にself.ageにする必要があります。


自己属性の使用は、オブジェクトのプロパティにアクセスし、オブジェクトのプロパティを参照するためのガイドラインであるため、OOPでは非常に重要です。

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

代わりのage命名arbitary、外部、グローバル変数をインクリメント:あなたはyearPasses方法にする必要があるのと同じ方法。

人間の言葉では、単にageを増やすことはありません。 この人の年齢を増やし、後でこの年を他の目的のために使用します。

+0

誤ってタイプミスが転写の意図しないエラーであった。あなたが 'self.age'で参照しているコードは、私がこの記事を書く前に期待していたように機能しません。 – Lc0rE

+1

'yearPasses'について追加した内容を見てください。エラーはコードから派生しています(コードで使用した場合)。 – Uriel

+0

コメントありがとうございます。現在、期待どおりに機能しています。私は、この問題を解決するために「グローバル時代」がいかに必要であるかを指摘していたディスカッションフォーラムのガイドラインに従った:/しかし、彼らは間違っていたと思う – Lc0rE

0

selfは、クラスオブジェクトの表現に使用されます。たとえば、コードを調べるとします。

人は、クラス(クラスPersonです:)そして、私たちのようなクラスのオブジェクトとして任意の名前を挙げることができる:

person.amIOld() #or 
per.amIOld() #here per is an object where we kept self as parameter in that function. 
:uはuは次のように呼び出す必要があります関数を呼び出すしたい場合は

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

しかし、コンパイラは関数の最初のパラメータをオブジェクト(自己)の表現として考えるため、自己を覚えておかなければならないことは、どの関数でも最初のパラメータにする必要があります。

さらに詳しい説明が必要な場合は、[email protected]で私にメッセージを送ってください。

関連する問題