先日私は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)
部分には、(代わりにage
のself.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:
の
'' 'self.age> = 13''ではなく' 'selfage> = 13'''を持っている可能性があります。 – Lolgast
申し訳ありませんが、私は意図しないタイプミスを修正しました。しかし、今でも、私が期待していたように動作していないので、コードの残りの部分に影響はありません。 – Lc0rE