Previous

Classes and Objects

2 / 5
Next

Not only do classes contain data attributes, they also have their own functions. Functions belonging to a class are called methods.

class Employee:
  salary = 0
  def give_raise(self, percentage):
    self.salary *= (1 + percentage / 100)

harald = Employee()
harald.salary = 4000
kaia = Employee()
kaia.salary = 5000

The class Employee has an attribute salary, and a method give_raise. The first parameter of the method is called self, and always refers to the object that is calling the method. In the method, the object's own attribute salary is accessed and modified with self.salary.

harald.give_raise(5)
print(harald.salary)   # output: 4200.0
print(kaia.salary)     # output: 5000.0

Notice that eveǹ though self is a method parameter, it is not passed as an argument. When harald.give_raise(5) is called, self will be the object harald automatically, and the percentage will be 5. Kaia's salary will remain unchanged; only object harald is calling the method give_raise.

Send

Methods

Hint
Beginner

Add the following two methods to 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.

Help
Solve
Reset
Run
Submit
 

Test results

Test result #
Expected output
Your output

Your email has been verified!