Python Glossary English

все Python 3ООПпонятие

__init__

инициализация

Конструктор — вызывается при создании экземпляра. Инициализирует атрибуты объекта.

Синтаксис

def __init__(self, params): ...

__init__ — не конструктор в полном смысле: к моменту его вызова объект уже создан методом __new__, а __init__ лишь заполняет атрибуты и обязан вернуть None (вернёте что-то другое — TypeError). При наследовании легко забыть super().__init__(), из-за чего часть родительской инициализации не отработает.

Примеры

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

См. также

Открыть в полном глоссарииdocs.python.orgСообщить о неточности