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 SolutionExpandCollapse
ExpandCollapse
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 TipsWant more? Click to expandClick to collapse
F. The Magic of Dot
- The dot
.means "Go inside". bot.name: Go insidebotand findname.bot.introduce(): Go insidebotand runintroduce.
Loading...
Terminal
Terminal
Ready to run...