如何在Python中使用全局变量来供所有类方法使用?

2024-06-16 08:45:15 发布

您现在位置:Python中文网/ 问答频道 /正文

  • 我有一个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,但现在它在调用时不执行任何操作

  • 我如何调整它使它工作?


Tags: theto方法inselfyouagedef
1条回答
网友
1楼 · 发布于 2024-06-16 08:45:15

您需要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()    

输出

^{pr2}$

你的原始代码有如下语句

age = initialAge 

在方法上。它只在方法中创建一个名为age的本地对象。这样的对象不存在于方法之外,并且在方法终止时被清除,因此下次调用该方法时,它的旧值age已丢失。在

self.age是类实例的属性。类的任何方法都可以使用self.age语法访问和修改该属性,并且该类的每个实例都有自己的属性,因此当您创建Person类的多个实例时,每个实例都将有自己的.age。在

也可以创建作为类本身属性的对象。它允许类的所有实例共享单个对象。例如

Person.count = 0

创建Person类的名为.count的类属性。也可以通过在方法外部放置赋值语句来创建类属性。例如

class Person:
    count = 0
    def __init__(self, initialAge):
        Person.count += 1
        # Add some more code to run some checks on initialAge
        #Etc

将跟踪到目前为止你的程序已经创建了多少个人实例。在

相关问题 更多 >