__init__ and self
Set up every new object automatically, with the data it needs from the start.
Code runs right here in your browser. Nothing to install.
Learn it
__init__ sets up every new object, and self means this object.
Setting attributes one by one is slow and easy to forget. The special method __init__ (two underscores each side, called "dunder init") runs automatically every time you create an object. Use it to set up the attributes.
Every method gets the object itself as its first parameter, called self by convention. Inside __init__, self.name = name means "store the name argument on this object".
Arguments you pass when creating the object go to __init__: Hero("Nova", 100) calls __init__(self, "Nova", 100). Python fills in self for you.
__init__ gives each new object its own details.class Hero: def __init__(self, name, health=100): self.name = name self.health = health self.items = [] nova = Hero("Nova") kai = Hero("Kai", 80) nova.items.append("torch") print(nova.name, nova.health, nova.items) print(kai.name, kai.health, kai.items)
Try it yourself
+10 XPWrite a class Spaceship whose __init__ takes a name and a fuel amount (default 100) and also sets passengers to 0. Create two ships and print Comet fuel 100 passengers 0 and Nebula fuel 45 passengers 0.
Create a free account to start this lab
Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.
Capture the flag
+10 XPWhat is the first parameter of every method conventionally called?
Create a free account to start this lab
Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.
Student records
+20 XPWrite a class Student with __init__(self, name, year) that also creates an empty marks list. Create two students, append some marks to each, and print each student's name, year and their marks list, like Ava (Year 10): [72, 88].
Create a free account to start this lab
Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.