我有一個
Person
類,它持有age
財產,現在我需要它裏面Person
類中的所有方法訪問,因此所有的方法正常工作如何在Python中爲所有類方法使用全局變量?我的代碼如下:
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開始有點奇怪,但像編程中的任何東西,有足夠的練習,它很快就會成爲熟悉的人 –