Get startedGet started for free

Adding methods and attributes

Now you'll start by creating methods that set attributes, and then add a few methods that manipulate them.

As mentioned in the first video, an object-oriented approach is most useful when your code involves complex interactions of many objects. In real production code, classes can have dozens of attributes and methods with complicated logic, but the underlying structure is the same as with the most simple class.

Your classes in this course will only have a few attributes and short methods, but the organizational principles behind them will be directly translatable to more complicated code.

This exercise is part of the course

Introduction to Object-Oriented Programming in Python

View Course

Exercise instructions

  • Add another method to the Employee class called set_salary() that will set the salary attribute of an object to the new_salary argument passed to the method.
  • Call the emp object's .set_name() method, assigning the value 'Korel Rossi'.
  • Call the method on the emp object and set the salary to 50000.
  • Print the salary attribute of the emp object.

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
  
  # Add set_salary() method  
  def ____(____, ____):
    ____.____ = ____ 

emp = Employee()

# Use set_name to set the name of emp to 'Korel Rossi'
emp.____('____')

# Set the salary of emp to 50000
____.____(____)

# Print the emp object's salary
print(____)
Edit and Run Code