Constructor

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Class Declaration

JS · Classes & OOP
Syntax
class ClassName {
  constructor(params) { ... }
  method() { ... }
}
Example
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  format() {
    return `${this.name}: $${this.price.toFixed(2)}`;
  }
}

const item = new Product("Notebook", 12.5);
console.log(item.format());
Output
"Notebook: $12.50"

Note Classes are syntactic sugar over prototypes. They are NOT hoisted -- you must declare before use, unlike function declarations.

PYPython

Defining a Class

PY · Classes & OOP
Syntax
class Name:
    def __init__(self, ...):
        self.attr = value
Example
class BankAccount:
    def __init__(self, owner: str, balance: float = 0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount: float) -> None:
        self.balance += amount

acct = BankAccount("Alice", 100)
acct.deposit(50)
print(f"{acct.owner}: ${acct.balance}")
Output
Alice: $150

Note self is not a keyword; it is a convention for the first parameter of instance methods. Python passes the instance automatically.

Frequently asked questions

How does JavaScript handle constructor?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Class Declaration" snippet in JavaScript uses `class ClassName {`.
Which code does the JavaScript example use?
The "Class Declaration" snippet uses `class ClassName {`, from the Classes & OOP section of the JavaScript cheat sheet.
Which stacks cover "constructor" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Class Declaration": Classes are syntactic sugar over prototypes. They are NOT hoisted -- you must declare before use, unlike function declarations.