IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Introduction to Object-Oriented Programming in Python

Visualizza il corso

Istruzioni dell'esercizio

  • Add a method give_raise() to the Employee class that increases the salary by the amount argument passed to give_raise().
  • Create the emp object.
  • Print the salary attribute of emp.
  • Call give_raise() on the emp object, increasing their salary by 1500.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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)
Modifica ed esegui il codice