Python Glossary Русский

all Python 3OOPterm

__init__

initialization

The constructor — called when an instance is created. It initializes the object's attributes.

Syntax

def __init__(self, params): ...

__init__ isn't the constructor in the full sense: by the time it runs the object already exists (created by __new__), and __init__ only fills in its attributes — it must return None, or you get a TypeError. In a subclass it's easy to forget super().__init__(), leaving part of the parent's setup undone.

Examples

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
p = Person('Alice', 30)
print(p.name, p.age)  # → Alice 30
class Rectangle:
    def __init__(self, w=1, h=1):
        self.w = w
        self.h = h
r = Rectangle()
print(r.w, r.h)  # → 1 1
class BankAccount:
    def __init__(self, owner, balance=0):
        if balance < 0:
            raise ValueError('Balance cannot be negative')
        self.owner = owner
        self.balance = balance
acc = BankAccount('Bob', 100)
print(acc.balance)  # → 100
class Animal:
    def __init__(self, name):
        self.name = name
class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed
d = Dog('Rex', 'Lab')
print(d.name, d.breed)  # → Rex Lab
class Stack:
    def __init__(self):
        self._data = []
    def push(self, item):
        self._data.append(item)
    def pop(self):
        return self._data.pop()
s = Stack()
s.push(1); s.push(2)
print(s.pop())  # → 2
class Vector:
    def __init__(self, *components):
        self.components = list(components)
v = Vector(1, 2, 3)
print(v.components)  # → [1, 2, 3]
class Config:
    def __init__(self, **settings):
        self.__dict__.update(settings)
cfg = Config(debug=True, level=2)
print(cfg.debug, cfg.level)  # → True 2

See also

Open in the full glossarydocs.python.orgReport an inaccuracy