Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / Python

object.__init__

Inicjalizator ustawia stan już utworzonej instancji i musi zwrócić None.

Wersja: Python 3.14; repository image, production runtime not attested

Składnia

def __init__(self, value):
    self.value = value

Inicjalizator ustawia stan już utworzonej instancji i musi zwrócić None.

object.__init__

Typowe tworzenie wywołuje go po __new__, gdy wynik jest instancją żądanej klasy. Nadpisując inicjalizator, wywołaj super().__init__(...), jeśli potrzebna jest inicjalizacja bazowa. Samo super() tworzy obiekt pośredniczący.

Child ustawia Ada i 4. Zwrócenie 7 z inicjalizatora Bad zgłasza TypeError.

calls=[]
class Other:
    def __new__(cls): return 'already made'
    def __init__(self): calls.append(1)
assert Other()=='already made' and not calls

Przykłady

class Base:
    def __init__(self, name): self.name = name
class Child(Base):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age
x = Child("Ada", 4)
print(x.name, x.age)
class Bad:
    def __init__(self): return 7
try: Bad()
except TypeError as exc: print(type(exc).__name__)

Wynik

Ada 4
TypeError

Child ustawia Ada i 4. Zwrócenie 7 z inicjalizatora Bad zgłasza TypeError.

Źródła