Classes and Objects

1 / 4

Classes allow us to create custom data types that contain both data and functions. For example:

class Person:
  def __init__(self, new_name):
    self.name = new_name

The code above defines a class Person. The class has one method (function) called __init__. This is actually a special method called the constructor.

The class has an attribute (data) called name, referred to in the constructor method as self.name. The constructor sets the attribute name to the given new_name.

Objects of this class can be created as follows:

p1 = Person("Harald")
p2 = Person("Zara")
print(p1.name) # output: Harald
print(p2.name) # output: Zara

This creates two objects p1 and p1 of class Person. Upon creation, the constructor method is called. The first object p1 calls the constructor with new_name equal to "Harald". The object p1 will be the argument used for the parameter self in the constructor definition. Thus, p1.name will be set to "Harald" when the object p1 is declared.

Class constructors

Create a class for a geometric Point with attributes x and y as coordinates on a 2D plane. The constructor should set the coordinates, both defaulting to value 0.

Congratulations!

You passed the !

Welcome!

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

Your email has been verified!