0Pricing
Mojo Academy · Lezione

Campi e metodo __init__

Inizializzi lo stato di una struct.

Campi e metodo __init__ è una lezione Mojo Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Mojo Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Mojo Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Fields Start Empty

Declaring fields gives a struct its shape, but it does not fill them in. You still need to set each field's starting value. 🧱

Meet __init__

The special method __init__ runs when you create an instance. Its job is to set up the struct's fields with real values.

fn __init__(out self):
    self.x = 0
    self.y = 0

The self Parameter

Inside __init__, self refers to the new instance being built. You assign to self.field to give that instance its data.

self.x = 0

Why out self

Writing out self tells Mojo this method is constructing the value, so self starts uninitialized and you must fill every field.

fn __init__(out self):

Taking Arguments

An initializer usually takes arguments so each instance can start with different data passed in by the caller.

fn __init__(out self, x: Int, y: Int):
    self.x = x
    self.y = y

Set Every Field

You must assign every field in __init__. Mojo will not let a struct exist with some fields left uninitialized.

Creating an Instance

To build a value, call the struct like a function. Mojo runs __init__ and hands you back a ready instance.

var p = Point(3, 4)

Reading a Field

Once built, reach a field with dot access. So p.x reads the x you stored when the instance was created.

print(p.x, p.y)

Arguments Map to Fields

A common pattern is naming arguments like the fields and assigning each across. This keeps the initializer easy to read.

self.x = x
self.y = y

Default Starting Values

You can give fields sensible defaults by assigning constants in __init__ when no useful argument is provided by the caller.

fn __init__(out self):
    self.x = 0
    self.y = 0

The Full Picture

Fields declare what data exists; __init__ decides its starting value. Together they turn a blueprint into a usable instance.

struct Point:
    var x: Int
    var y: Int
    fn __init__(out self, x: Int, y: Int):
        self.x = x
        self.y = y

Quick Check

Let us confirm how initialization works.

Recap

You used __init__ to set up fields when an instance is born. Next you will add methods so your type can act, not just hold data. ✨

Domande Frequenti

La lezione «Campi e metodo __init__» è gratuita?

Sì — il testo completo di «Campi e metodo __init__» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Mojo Academy, passa a CoddyKit PRO. Il corso Mojo Academy include 4 lezioni in totale.

Cosa imparerò in «Campi e metodo __init__»?

Inizializzi lo stato di una struct. Eserciti Mojo Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Mojo Academy?

Non è richiesta alcuna esperienza precedente. Mojo Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Campi e metodo __init__»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Mojo Academy?

Sì. Ogni lezione Mojo Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Definire una struct
  2. Campi e metodo __init__
  3. Aggiungere metodi a una struct
  4. Struct e classi Python a confronto
← Torna a Mojo Academy