Using attributes in class definition
In the previous exercise, you defined an Employee
class with two attributes and two methods setting those attributes. This kind of method, aptly called a setter method, is far from the only possible kind. Methods are functions, so anything you can do with a function, you can also do with a method. For example, you can use methods to print, return values, make plots, and raise exceptions, as long as it makes sense as the behavior of the objects described by the class (an Employee
probably wouldn't have a pivot_table()
method).
In this exercise, you'll go beyond the setter methods and learn how to use existing class attributes to define new methods. The Employee
class and the emp
object from the previous exercise are in your script pane.
This exercise is part of the course
Object-Oriented Programming in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
class Employee:
def set_name(self, new_name):
self.name = new_name
def set_salary(self, new_salary):
self.salary = new_salary
emp = Employee()
emp.set_name('Korel Rossi')
emp.set_salary(50000)
# Print the salary attribute of emp
____
# Increase salary of emp by 1500
emp.salary = ____ + ____
# Print the salary attribute of emp again
____