🐸

The Birth

Python Basicspython-architect-18-the-birth
Reward: 100 XP
|

A blueprint is useless if every house looks exactly the same. We need customization!

When a robot is born (created), we want to give it a unique name and paint job immediately.

The __init__ Spell

This is a special spell (method) that runs automatically the moment an object is created. It determines the "Construction Settings".

class Cat:
  def __init__(self, name):
      self.name = name

# "name" is passed to __init__
kitty = Cat("Luna") 
print(kitty.name) # Luna
1
Define __init__

Inside Robot, define def __init__(self, name, color):.

2
Store Data

Inside __init__, save the values: self.name = name and self.color = color. self means "this specific robot I am building right now".

3
Build Custom Robots

Create bot1 with Robot("R2", "Blue") and bot2 with a different name/color.

It is spelled __init__ with two underscores on each side! It stands for "initialize".

Suggested Solution
Expand
Solution:
class Robot:
  def __init__(self, name, color):
      self.name = name
      self.color = color

# Build R2-D2
bot1 = Robot("R2", "Blue")

# Build C-3PO
bot2 = Robot("C3", "Gold") 

# Print their details
print("Bot 1: " + bot1.name + " (" + bot1.color + ")")
print("Bot 2: " + bot2.name + " (" + bot2.color + ")")
Advanced Tips
Want more? Click to expand

F. Attributes

  • Variables inside an object (like self.name and self.color) are called Attributes.
  • Each object has its own set of attributes. Changing bot1.name does not change bot2.name. They are independent minds!
Loading...
Terminal
Terminal
Ready to run...