Classes and Objects

3 / 4

The constructor method __init__ is a special method that is always called when creating a new object. Similarly, the method __str__ is a special method that is always called when printing an object.

class Employee:
  def __init__(self, employee_name):
    self.name = employee_name
  def __str__(self):
    return f"Employee with name {self.name}"

e1 = Employee("Harald")
print(e1) # outputs "Employee with name Harald"

The method __str__ returns a formatted string which is used to represent the object as a string. When printing, the object is converted to a string using this method.

Printing objects

Modify the code so that we can print objects of class Point.

If we do p = Point(3,4) then print(p) should output Point at (3,4).

Congratulations!

You passed the !

Welcome!

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

Your email has been verified!