If you have to stick to using this specific structure, I'd do it like this:
class Scholar:
_ACADEMIC_POSITIONS_BONUS_MAP = {
'Professor': 70000,
'Associate Professor': 50000,
'Assistance Professor': 30000,
}
def __init__(self, name, salary, academic_position):
self.name = name
self.salary = salary
self.academic_position = academic_position
@property
def bonus(self):
for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():
if self.academic_position == academic_position:
return bonus
raise ValueError(
f"Invalid academic position. Allowed: "
f"{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}"
)
And as other have mentioned, instead of iterating through the dict itself you can just do this:
class Scholar:
# ...
@property
def bonus(self):
return self._ACADEMIC_POSITIONS_BONUS_MAP[self.academic_position]
We've created a map between each type of academic_position
and its specific bonus
and a @property
where we return the bonus.
And then you can use it like this:
professor = Scholar("John Doe", 30000, "Professor")
associate_professor = Scholar("Associate John Doe", 30000, "Associate Professor")
assistance_professor = Scholar("Assistance John Doe", 30000, "Assistance Professor")
print(professor.bonus)
print(associate_professor.bonus)
print(assistance_professor.bonus)
Now, when you need to add another academic_position
, you just have to modify _ACADEMIC_POSITIONS_BONUS_MAP
.
Next, in order to calculate the yearly salary, just create another method within your class:
class Scholar:
# ...
def get_yearly_salary(self):
# Note: multiply the salary with 12 if it's monthly-based
return self.salary + self.bonus
Note: I'm not sure if @property
is the best way of doing this. You could've just done something along the lines:
class Scholar:
_ACADEMIC_POSITIONS_BONUS_MAP = {
'Professor': 70000,
'Associate Professor': 50000,
'Assistance Professor': 30000,
}
def __init__(self, name, salary, academic_position):
self.name = name
self.salary = salary
self.academic_position = academic_position
self.bonus = self.get_bonus()
def get_bonus(self):
for academic_position, bonus in self._ACADEMIC_POSITIONS_BONUS_MAP.items():
if self.academic_position == academic_position:
return bonus
raise ValueError(
f"Invalid academic position. Allowed: "
f"{', '.join(self._ACADEMIC_POSITIONS_BONUS_MAP)}"
)