Initialize

Constructor (C#)

A constructor in C# is a special method inside a class that runs automatically when you create an object with new.

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

Defining a Constructor#

A constructor has the same name as the class and no return type — not even void.

public class Player
{
    public string Name;

    public Player(string name)
    {
        Name = name;
    }
}

Name = name stores the argument on the object so it’s available later.

Constructor (JavaScript)

In JavaScript, the constructor is a special method inside a class that runs automatically when you create an object with new.

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

Defining a Constructor#

The constructor method is always named constructor. It receives arguments and uses this to store them on the object.

class Player {
    constructor(name) {
        this.name = name;
    }
}

Creating an Object#

Pass arguments to new when creating the object. JavaScript calls constructor automatically.

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.