如何为Python中的所有class方法使用一个全局变量?

How to use a global variable for all class methods in 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("")

您需要 age 成为 Person class 的实例属性。为此,您可以使用 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 是 class 实例的属性。 class 的任何方法都可以使用 self.age 语法访问和修改该属性,并且 class 的每个实例都有自己的属性,因此当您创建 Person class每一个都会有自己的.age

也可以创建作为 class 本身属性的对象。这允许 class 的所有实例共享一个对象。例如,

Person.count = 0

创建人物 class 的名为 .count 的 class 属性。您还可以通过将赋值语句放在方法外部来创建 class 属性。例如,

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

将跟踪您的程序到目前为止创建了多少个 Person 实例。