The other day I was trying on some easy exercises in Python3 and, since I'm pretty new in Python, I have some doubts about the
self
4
-1
10
16
18
class Person:
def __init__(self,initialAge):
# Add some more code to run some checks on initialAge
if initialAge < 0:
self.age = 0
print("Age is not valid, setting age to 0.")
else:
self.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.")
elif age >= 18:
print("You are old.")
def yearPasses(self):
# Increment the age of the person in here
global age
age += 1
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("")
def amIOld(self)
self.age
age
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 self.age >= 13 and self.age < 18:
print("You are a teenager.")
elif self.age >= 18:
print("You are old.")
Because of the line
elif selfage >= 13 and self.age < 18:
You are having a typo; That should be
self.age over there, to access the
age attribute of the class.
Using the self attributes is pretty crucial in OOP, because it is the guideline to accessing and regarding object's properties. The same way you should make the
yearPasses method:
def yearPasses(self): self.age += 1 # increment the self attribute of age
instead of incrementing an arbitary, external, global variable named
age.
In human terms - you don't increase just an
age; you increase the age of this person, and later you will use this age for other purposes.