CKTIS / Python
object.__init__
Inicializátor nastavuje stav už vytvorenej inštancie a musí vrátiť None.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
def __init__(self, value):
self.value = valueInicializátor nastavuje stav už vytvorenej inštancie a musí vrátiť None.
object.__init__
Bežná konštrukcia ho zavolá po __new__, ak je výsledok inštanciou požadovanej triedy. Prepísaný inicializátor volá super().__init__(...), ak potrebuje inicializáciu základu. Samotné super() vytvorí zástupný objekt.
Child nastaví Ada a 4. Vrátenie 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
Prí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ýsledok
Ada 4 TypeError
Child nastaví Ada a 4. Vrátenie 7 v Bad vyvolá TypeError.