🐸

The Action

Python Basicspython-architect-19-the-action
Reward: 100 XP
|

Our robots have bodies (data/names), but they just sit there. We need them to do things.

In the Blueprint (Class), we can write spells that let objects take action. These are called Methods.

The self Secret

A method looks exactly like a function, but it lives inside a class. Crucial Rule: The first argument must always be self.

  • self = "Me".
  • self.name = "My name".
class Dog:
  def __init__(self, name):
      self.name = name

  def bark(self):
      print(self.name + " says Woof!")

dog = Dog("Rex")
dog.bark() # Rex says Woof!
1
Define the Method

Inside Robot, define def introduce(self):.

2
Use Self

Inside the method, print "Hello, I am " + self.name. Using self.name allows the robot to know its own name!

3
Make it Speak

Create a robot and call bot.introduce(). Notice we don't pass self when calling it; Python handles that magic for us.

Why do we need self? Because if you have 100 robots, Python needs to know which specific robot is speaking!

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

  def introduce(self):
      print("Hello, I am " + self.name)

bot = Robot("Wall-E")
bot.introduce()
Advanced Tips
Want more? Click to expand

F. The Magic of Dot

  • The dot . means "Go inside".
  • bot.name: Go inside bot and find name.
  • bot.introduce(): Go inside bot and run introduce.
Loading...
Terminal
Terminal
Ready to run...