我有一个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,但现在它在调用时不会做任何事情
我如何调整它以使其有效?
答案 0 :(得分:2)
您需要age
作为Person类的实例属性。为此,您使用self.age
语法,如下所示:
class Person:
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.")
self.age = 0
self.age = initialAge
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 13 <= self.age <= 19:
print("You are a teenager.")
else:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
self.age += 1
#test
age = 12
p = Person(age)
for j in range(9):
print(j, p.age)
p.amIOld()
p.yearPasses()
<强>输出强>
0 12
You are young.
1 13
You are a teenager.
2 14
You are a teenager.
3 15
You are a teenager.
4 16
You are a teenager.
5 17
You are a teenager.
6 18
You are a teenager.
7 19
You are a teenager.
8 20
You are old.
您的原始代码有
之类的陈述age = initialAge
在其方法中。这只是在方法中创建一个名为age
的本地对象。这些对象在方法外部不存在,并在方法终止时被清除,因此下次调用方法时,其旧值age
已丢失。
self.age
是类实例的属性。该类的任何方法都可以使用self.age
语法访问和修改该属性,并且该类的每个实例都有自己的属性,因此当您创建Person类的多个实例时,每个实例都有自己的{{1 }}。
也可以创建属于类本身属性的对象。这允许类的所有实例共享单个对象。例如,
.age
创建Person类的名为Person.count = 0
的类属性。您还可以通过在方法外部放置赋值语句来创建类属性。例如,
.count
将跟踪您的程序到目前为止创建的Person实例数。