Extending a class
In the previous exercise, you defined an Employee class with two attributes and two methods that set those attributes. Remember, 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 or return values, or to make plots, as long as the behavior is appropriate for objects of that class, e.g., an Employee probably wouldn't have a pivot_table() method.
In this exercise, you'll 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.py.
Latihan ini adalah bagian dari kursus
Introduction to Object-Oriented Programming in Python
Petunjuk latihan
- Add a method
give_raise()to theEmployeeclass that increases the salary by theamountargument passed togive_raise(). - Create the
empobject. - Print the
salaryattribute ofemp. - Call
give_raise()on theempobject, increasing their salary by1500.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
class Employee:
def set_name(self, new_name):
self.name = new_name
def set_salary(self, new_salary):
self.salary = new_salary
# Add a give_raise() method with amount as an argument
____ ____(____, ____):
____.____ = ____.____ + ____
# Create the emp object
emp = ____
emp.set_name('Korel Rossi')
emp.set_salary(50000)
# Print the salary
print(____.____)
# Give emp a raise of 1500
____.____(____)
print(emp.salary)