Home > Software design >  passing values between methods, Python OOP, Method not getting
passing values between methods, Python OOP, Method not getting

Time:09-17

I am learning about classes and methods, trying to modify a simple python code so I can pass an attribute value using a method. I could pass the attribute for the setyear() method. However, I am unable to use it and perform a simple mathematical operation (e.g, age calculation) as in the agecalc() method. Wonder if you can please point out why am I getting 0 instead of 10?

class Dog:
    def __init__(self, name, born, breed):
        self.name = name
        self.born = born     # year born
        self.breed = breed
        self.year = 0
        self.age=0
  
    
    def setyear(self, year):
        #self.year = year-self.born     
        self.year = year
    
    def agecalc(self, year):
        self.age = self.year - self.born  ##*** keeps giving me 0??
        

mydog1 = Dog (name = "Lassy", born = 2015, breed = "Husky") 

mydog1.setyear(2025) # setting the year we wish to calculate the dog's age at
   

# The following is sub ideal. 
print ("dog age =", mydog1.year - mydog1.born)  
# looking replace the above line with the agecalc method i.e. print (agecalcl(2025))


# Tried the following one as well and it keeps giving me `None`
print (mydog1.agecalc(2025))

CodePudding user response:

You didn't return the age; you only set an attribute.

mydog1.agecalc(2025)
print(mydog1.age)

Alternatively, you can have agecalc return the age instead of storing the age. The current year isn't really a property of the dog like its birth year is.

class Dog:
    def __init__(self, name, born, breed):
        self.name = name
        self.born = born     # year born
        self.breed = breed
  
    
    def agecalc(self, year):
        return year - self.born
        

mydog1 = Dog(name="Lassy", born=2015, breed="Husky") 
print("My dog is", mydog1.agecalc(2025), "years old.")

CodePudding user response:

your function should be this:

def agecalc(self, year):
    self.age = year - self.born
    return self.age

you mixed up year (the year you pass in as an argument) with self.year

also, you print, so I guess you want to return the value or access the age directly (not so OOP'ish, but python allows it)

mydog1.agecalc(2025)
print(mydog1.age)

CodePudding user response:

you are missing the return statement try:

def agecalc(self, year):
    self.age = year - self.born
    return self.age
  • Related