Previous

Classes and Objects

1 / 5
Next

Classes allow us to encapsulate multiple data attributes in a single object.

class Person:
  name = "default name"
  age = 0

The code above defines a class Person. The class has two data attributes name and age. The values of these attributes default to "New person" and 0.

p = Person()
print(p.name) # default name
p.name = "Harald"
print(p.name) # Harald

An object of class Person is created with parentheses and assigned to the variable p. The name of the person is overwritten with Harald. This is done using object access notation with a dot: p.name.

Send

Attributes

Hint
Beginner

Define a class Point with class attributes x = 0 and y = 0 as coordinates on the $xy$-plane.

Declare an object p of class Point and set the coordinates p.x = 5 and p.y = 3.

Help
Solve
Reset
Run
Submit
 

Test results

Test result #
Expected output
Your output

Your email has been verified!