我有一个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,但现在它在调用时不执行任何操作
我如何调整它使它工作?
您需要
age
作为Person类的实例属性。为此,可以使用self.age
语法,如下所示:输出
^{pr2}$你的原始代码有如下语句
在方法上。它只在方法中创建一个名为
age
的本地对象。这样的对象不存在于方法之外,并且在方法终止时被清除,因此下次调用该方法时,它的旧值age
已丢失。在self.age
是类实例的属性。类的任何方法都可以使用self.age
语法访问和修改该属性,并且该类的每个实例都有自己的属性,因此当您创建Person类的多个实例时,每个实例都将有自己的.age
。在也可以创建作为类本身属性的对象。它允许类的所有实例共享单个对象。例如
创建Person类的名为
.count
的类属性。也可以通过在方法外部放置赋值语句来创建类属性。例如将跟踪到目前为止你的程序已经创建了多少个人实例。在
相关问题 更多 >
编程相关推荐