BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Introduction to Object-Oriented Programming in Python

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • 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.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

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(____)
Kodu Düzenle ve Çalıştır