__Init__

Class (Python)

A class in Python is a blueprint for creating objects, defined with the class keyword.

This page covers Class in Python. For a language-agnostic introduction, see Class.

Defining a Class#

class Player:
    pass

pass is a placeholder that means “empty body”. By convention, class names use PascalCase: Player, OddsAndEvens, RockPaperScissors.

Adding a Constructor#

In Python, the constructor is a special method called __init__. It runs automatically when an object is created. The first parameter is always self — a reference to the object being created.

Constructor

A constructor is a special method that runs automatically when an object is created from a class. Its job is to set up the object’s initial state.

  new Player("Alice")
  ┌─────────────────────┐
  │     constructor     │  ← runs automatically
  │  sets name = Alice  │
  └─────────────────────┘
  Player object ready

What a Constructor Does#

When you create an object, you often need to give it some starting values — a name, a score, a position. The constructor receives those values as arguments and stores them on the object.

Constructor (Python)

In Python, the constructor is a special method called __init__. It runs automatically when you create an object from a class.

This page covers Constructor in Python. For a language-agnostic introduction, see Constructor.

Defining __init__#

Like all instance methods in Python, __init__ takes self as its first parameter. Additional parameters receive the values passed when creating the object.

class Player:
    def __init__(self, name):
        self.name = name

self.name = name stores the argument on the object.