🐸

The Team

Python Basicspython-architect-21-the-team
Reward: 100 XP
|

Robots don't just live in isolation; they work together.

In Python, you can pass an Object into a function (or method), just like you pass a number.

Object Interaction

If alice and bob are both Robots, alice can interact with bob.

class Healer:
  def heal(self, target):
      print("Healing " + target.name)

cleric = Healer()
warrior = Hero("Conan")

# Pass the warrior OBJECT to the heal method
cleric.heal(warrior) # "Healing Conan"
1
Define Greeting

Define def greet(self, target):. Here, target will be another robot object.

2
Use Two Objects

Inside the method, you can access self.name (the greeter) AND target.name (the friend). Print "Hello " + target.name from self.name.

3
Connection

Call r1.greet(r2). We are passing the entire r2 object into r1's world!

This is the foundation of game engines. Player attacks Enemy. Car hits Wall. Objects interacting with objects!

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

  def greet(self, target):
      print(self.name + " says hello to " + target.name)

r1 = Robot("HoppyBot")
r2 = Robot("PyBot")

r1.greet(r2)
Advanced Tips
Want more? Click to expand

F. Infinite Interactions

  • You can pass objects to objects.
  • You can put objects inside lists (team = [r1, r2]).
  • You can even put objects inside other objects (r1.best_friend = r2).
  • This is how complex software is built!
Loading...
Terminal
Terminal
Ready to run...