有一天我在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.")
誰能這麼好心給我解釋的差異?
謝謝!
可能是因爲你有'''selfage> = 13'''而不是''self.age> = 13''' – Lolgast
對不起,我糾正了無意的錯字。但即使是現在它對代碼的其餘部分也沒有影響,因爲它並不像我期待的那樣工作。 – Lc0rE