IniziaInizia gratis

Add a class constructor

In this exercise, you'll continue working on the Employee class. Instead of using the methods like set_salary() that you wrote in the previous lesson, you will introduce a constructor that assigns name and salary to the employee at the moment when the object is created.

Initializing attributes in the constructor is a good idea because this ensures that the object has all the necessary attributes the moment it is created.

Questo esercizio fa parte del corso

Introduction to Object-Oriented Programming in Python

Visualizza il corso

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

class Employee:
  # Create __init__() method
  ____ ____(____, name, ____):
    # Create the name and salary attributes
    self.____ = ____
    ____ = ____
    
  def give_raise(self, amount):
    self.salary += amount

  def monthly_salary(self):
    return self.salary / 12
        
emp = Employee("Korel Rossi")
print(emp.name)
print(emp.salary)     
Modifica ed esegui il codice