0Pricing
Python Academy · Lesson

Classes and the __init__ Method

Define classes, create objects, and initialize attributes.

Defining a Class

Use the class keyword to define a class. By convention, class names use CapWords.

class Dog:
    pass

fido = Dog()
print(type(fido))  # <class '__main__.Dog'>

The __init__ Method

__init__ is called automatically when an object is created. Use it to set up instance attributes.

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

fido = Dog("Fido", "Labrador")
print(fido.name)   # Fido

All lessons in this course

  1. Classes and the __init__ Method
  2. Instance vs Class Attributes
  3. Instance Methods and self
  4. Magic Methods: __str__ and __repr__
← Back to Python Academy