Python · Stage 9 – Intro to Objects · Lesson 46 of 50

A Class with Attributes and Methods

Build one small class whose objects store a name and perform one action.

class Dog:
    def __init__(self, name):
        self.name = name
Line-by-line explanation
  1. The class definition begins.
  2. __init__ receives a new object and a name.
  3. self.name is an attribute on that object.
  4. The passed name is stored there.
    def bark(self):
        print("Woof!")
Line-by-line explanation
  1. This indented definition belongs to Dog.
  2. bark is a method.
  3. Calling it displays Woof.
pet = Dog("Milo")
pet.bark()
Line-by-line explanation
  1. A Dog object is created with the name Milo.
  2. pet stores it.
  3. The bark method is called on that object.