【发布时间】:2017-01-12 00:53:54
【问题描述】:
-
我有一个
李>Person类,它拥有一个age属性,现在我需要让它在Person类内的所有方法中都可以访问,以便所有方法都能正常工作 我的代码如下:
class Person:
#age = 0
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
if(initialAge < 0):
print("Age is not valid, setting age to 0.")
age = 0
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.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
Person.age += 1 # I am having trouble with this method
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("")
yearPasses()应该将age增加 1,但现在调用时它什么也不做如何对其进行调整以使其发挥作用?
【问题讨论】:
-
@PM2Ring 实际上,我是对象编程的新手......甚至不知道如何描述我的问题(逃跑
-
OOP 一开始有点陌生,但就像编程中的任何事情一样,只要练习足够多,很快就会熟悉。
标签: python class object methods instance