Can't get function within object to display value
Question:
hey guys I’m currently learning oop but I’m having a bit of trouble with accessing values which I create or add to a object, currently I can’t work out how to get the value stored within getAge
from datetime import date
class Person:
def __init__(self, name, dob, cob):
self.name = name
self.dob = dob
self.cob = cob
def setName(self, name):
self.name = name
def getAge(self):
today = date.today()
birthYear = int(self.dob[6:]) + 2000
age = today.year - birthYear
return age
p1 = Person('Jane', '22/06/02', 'England')
p1.setName("Joe")
print(p1.name)
print(Person.getAge)
Answers:
I don’t understand why you print Person.getAge
, it’s a method of Person
.
getAge
is a method and not static not, so you need use p1.getAge()
istead of Person.getAge
to get the age
value.
The method getAge only makes sense when using it on an instance of the Person ss. In your case print(p1.getAge())
to activate the method.
You could also add the @propery
decorator above the method to avoid the parentheses as the method doesn’t require any arguments.
hey guys I’m currently learning oop but I’m having a bit of trouble with accessing values which I create or add to a object, currently I can’t work out how to get the value stored within getAge
from datetime import date
class Person:
def __init__(self, name, dob, cob):
self.name = name
self.dob = dob
self.cob = cob
def setName(self, name):
self.name = name
def getAge(self):
today = date.today()
birthYear = int(self.dob[6:]) + 2000
age = today.year - birthYear
return age
p1 = Person('Jane', '22/06/02', 'England')
p1.setName("Joe")
print(p1.name)
print(Person.getAge)
I don’t understand why you print Person.getAge
, it’s a method of Person
.
getAge
is a method and not static not, so you need use p1.getAge()
istead of Person.getAge
to get the age
value.
The method getAge only makes sense when using it on an instance of the Person ss. In your case print(p1.getAge())
to activate the method.
You could also add the @propery
decorator above the method to avoid the parentheses as the method doesn’t require any arguments.