CKTIS / Python
object.__init__
Inicializátor nastavuje stav již vytvořené instance a musí vrátit None.
Verze: Python 3.14; repository image, production runtime not attested
Syntaxe
def __init__(self, value):
self.value = valueInicializátor nastavuje stav již vytvořené instance a musí vrátit None.
object.__init__
Běžná konstrukce jej zavolá po __new__, pokud je výsledek instancí požadované třídy. Přepsaný inicializátor volá super().__init__(...), pokud potřebuje inicializaci základu. Samotné super() vytvoří zástupný objekt.
Child nastaví Ada a 4. Vrácení 7 v Bad vyvolá TypeError.
calls=[]
class Other:
def __new__(cls): return 'already made'
def __init__(self): calls.append(1)
assert Other()=='already made' and not calls
Příklady
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__)
Výsledek
Ada 4 TypeError
Child nastaví Ada a 4. Vrácení 7 v Bad vyvolá TypeError.