Lc0rE - 1 year ago 73
Python Question

# Use of self in Python

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`
concept.

Below an exercise taken from HackerRank's 30-days-ofcode challenge.
Based on the input's values, I have to evaluate one person's age printing out differents outputs:

Input (stdin)

``````4
-1
10
16
18
``````

Code

``````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
``````

And then

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

What I'm wondering is why in the
`def amIOld(self)`
part, the code below (with the use of
`self.age`
`age`
) is not working:

``````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.")
``````

Can anyone be so kind to explain me the difference?

Thanks!

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download