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 SolutionExpandCollapse
ExpandCollapse
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 TipsWant more? Click to expandClick to collapse
F. Attributes
- Variables inside an object (like
self.nameandself.color) are called Attributes. - Each object has its own set of attributes. Changing
bot1.namedoes not changebot2.name. They are independent minds!
Loading...
Terminal
Terminal
Ready to run...