What is the need to define a function to return a class's attribute?
Question:
I came across some code like this
class Student(Person):
def __init__(self, age):
self.age = age
def get_age(self):
return self.age
Could you please explain the purpose of the function get_age()
? If we want to know a student’s age, can’t we simply do this:
student = Student(20)
student_age = student.age
Answers:
Instead of a function like get_age
, a property should be used. Both approaches have the advantage over a direct attribute access that later changes to the way how the requested data is retrieved by the object don’t require changes to the way the data is accessed from outside of the object.
Example:
Initial code:
class Student:
def __init__(self, age):
self._age = age
@property
def age(self):
return self._age
print(Student(23).age)
Can be changed (just an example, don’t do date calculation like that) to:
from datetime import date
class Student:
def __init__(self, age):
self._birthyear = date.today().year - age
@property
def age(self):
return date.today().year - self._birthyear
print(Student(23).age)
The last line accessing the age didn’t change.
I came across some code like this
class Student(Person):
def __init__(self, age):
self.age = age
def get_age(self):
return self.age
Could you please explain the purpose of the function get_age()
? If we want to know a student’s age, can’t we simply do this:
student = Student(20)
student_age = student.age
Instead of a function like get_age
, a property should be used. Both approaches have the advantage over a direct attribute access that later changes to the way how the requested data is retrieved by the object don’t require changes to the way the data is accessed from outside of the object.
Example:
Initial code:
class Student:
def __init__(self, age):
self._age = age
@property
def age(self):
return self._age
print(Student(23).age)
Can be changed (just an example, don’t do date calculation like that) to:
from datetime import date
class Student:
def __init__(self, age):
self._birthyear = date.today().year - age
@property
def age(self):
return date.today().year - self._birthyear
print(Student(23).age)
The last line accessing the age didn’t change.