在此hackerrank挑战中,我想编写一个Person类,该类具有一个实例变量 age ,以及一个构造函数,该构造函数将整数 initialAge 作为参数。确认传递的参数不是负数之后,构造函数必须将 initialAge 分配给 age ;如果将负参数传递为,则构造方法应设置为,并且print Age无效,将age设置为0。此外,您必须编写以下实例方法:
这是代码:
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
self.initialAge = age
def amIOld(self):
# Do some computations in here and print out the correct statement to the console
if age <= 0:
age is 0
print("Age is not valid, setting age to 0")
elif age < 13:
print("You are young.")
elif 13 <= age < 18:
print("You are teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
return 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("")
这是输入:
4
-1
10
16
18
这是预期的输出:
Age is not valid, setting age to 0.
You are young.
You are young.
You are young.
You are a teenager.
You are a teenager.
You are old.
You are old.
You are old.
这是我的输出:
Age is not valid, setting age to 0
Age is not valid, setting age to 0
You are young.
You are young.
You are teenager.
You are teenager.
You are old.
You are old.
我的代码怎么了?
答案 0 :(得分:2)
所有解决方案均以良好的方式完成,但输出不正确。以下解决方案以相同的方式完成,但正确。看一下以下解决方案:
class Person:
def __init__(self,initialAge):
self.age = initialAge
if self.age <=0:
print('Age is not valid, setting age to 0.')
# Add some more code to run some checks on initialAge
def amIOld(self):
if self.age < 13:
print('You are young.')
elif (13<=self.age< 18):
print('You are a teenager.')
else:
print('You are old.')
# Do some computations in here and print out the correct statement to the console
def yearPasses(self):
self.age +=1
# Already provided by Hackerank in the challenge!
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("")
答案 1 :(得分:0)
我认为这里有很多需要改进的地方,尤其是考虑使用实例变量的情况。
class Person:
'''The init method seems strange to me, as you seem to have mixed up the order
of the expression. It should be the other way round.'''
def __init__(self, initialAge):
# order correct now
self.age = initialAge
def amIOld(self):
# age was used locally here, but should reference the instance variable
if self.age < 0:
self.age = 0
print("Age is not valid, setting age to 0")
elif self.age < 13:
print("You are young.")
elif 13 <= self.age < 18:
print("You are teenager.")
else:
print("You are old.")
def yearPasses(self):
# no need to return anything here, as you just alter the instance var
self.age += 1
# hint: you can just use range(t) as the default start val is 0
t = int(input())
for i in range(t):
age = int(input())
p = Person(age)
p.amIOld()
for j in range(3):
p.yearPasses()
p.amIOld()
print("")
我的机器上的输出是:
Age is not valid, setting age to 0
You are young.
You are young.
You are teenager.
You are teenager.
You are old.
You are old.
You are old.