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.