Classes and Objects

2 / 4

The constructor method __init__ is a special method that is always called when creating a new object. It is not possible to choose a different name for it. You can add other methods with arbitrary names. For example, in a database for some business, we could have:

class Employee:
  def __init__(self, employee_name):
    self.name = employee_name
    self.salary = 0
  def set_salary(self, new_salary):
    self.salary = new_salary
e1 = Employee("Harald")
e2 = Employee("Zara")
e1.set_salary(4000) # Harald earns 4000 a month
e2.set_salary(5000) # Zara earns 5000 a month

The class Employee has two methods: a constructor and set_salary. It also has two attributes: name and salary. The method set_salary updates the salary of an employee.

Custom methods

Add the following two methods the the class Point:

  • A method translate with two parameters dx and dy. The method should move the point with these distances.
  • A method distance with one parameter p which should be another point. The method should return the distance between the point self and p.

Hint: the distance between point $(x_1,y_1)$ and point $(x_2,y_2)$ is $\sqrt{(x_2-x_1)^2 + (y_2-y_1)^2}$.
Use the function math.sqrt to compute the square root.
Use x**2 to square a variable x.

Congratulations!

You passed the !

Welcome!

Would you like a guided tour on how to use Vibewise?

Your email has been verified!