jm33_m0 jm33_m0 - 3 months ago 9
Python Question

How to use a global variable for all class methods in Python?


  • I have a
    Person
    class, which holds an
    age
    property, now I need to make it accessible in all method inside
    Person
    class, so that all methods work properly

  • My code is as following:



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()
    is supposed to increase the
    age
    by 1, but now it doesn't do anything when called

  • How do I adapt it to make it work?


Answer

You need age to be an instance attribute of the Person class. To do that, you use the self.age syntax, like this:

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()    

output

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.

Your original code had statements like

age = initialAge 

in its methods. That just creates a local object named age in the method. Such objects don't exist outside the method, and are cleaned up when the method terminates, so the next time you call the method its old value of age has been lost.

self.age is an attribute of the class instance. Any method of the class can access and modify that attribute using the self.age syntax, and each instance of the class has its own attributes, so when you create multiple instances of the Person class each one will have its own .age.

It's also possible to create objects which are attributes of the class itself. That allows all instances of the class to share a single object. Eg,

Person.count = 0

creates a class attribute named .count of the Person class. You can also create a class attribute by putting an assignment statement outside a method. Eg,

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

would keep track of how many Person instances your program has created so far.