Lesson 7 - Classes & Objects

Python Classes and Objects

Classes and Objects in Python:

class Hero:
  def __init__(self, name, health):
    # self lets each object store its own data
    self.name = name
    self.health = health

  def __str__(self):
    return f"Hero {self.name} with {self.health} health"

  def say(self, words):
    print(self.name, "says:", words)

# Create two heroes (objects)
h1 = Hero("Alex", 100)
h2 = Hero("Maya", 80)

print(h1)
print(h2)
h1.say("Let's fight!")

- A class is a blueprint for creating objects.
- An object is an instance (copy) created from the class.
- self refers to the object itself. It lets each object keep its own data.

The __init__ method

- This is a special function that runs when you create a new object.
- It is often used to set up initial values (like a name, score, or health).

The __str__ method

- Another special function that controls what gets printed when you use print(object).
- It should return a string that describes the object in a nice way.

πŸ‘‰ In this example:

⚫__init__ sets up each hero’s name and health when it is created.
⚫__str__ makes print(h1) show a nice message instead of something confusing.
⚫self makes sure each object has its own values for name and health.

What is a Class?

A class is like a blueprint (or plan) to create objects. For example, if you have a blueprint of a house, you can use it to build many houses. In Python, a class can be used to create many objects with the same structure but different data.

Objects

An object is something created from a class. If a class is a blueprint, then an object is the actual house built from it.

Example

class Dog:
  def bark(self):
    print("Woof! 🐢")

# Create an object from the class
myDog = Dog()
myDog.bark()

Explanation:

  • class Dog: defines the class Dog.
  • bark() is a function inside the class. Functions in a class are also called methods.
  • myDog = Dog() creates an object from the class.
  • myDog.bark() makes the dog object use the bark method β†’ it prints "Woof! 🐢".

Create a Simple Class

class Animal:
  def sound(self):
    print("Some sound")

myAnimal = Animal()
myAnimal.sound()

πŸ’‘ Try changing "Some sound" to "Meow" or "Woof".

Dog Class

class Dog:
  def bark(self):
    print("Woof! 🐢")

dog = Dog()
dog.bark()

πŸ’‘ Add another function called eat that prints "The dog is eating."

Cat Class with Multiple Methods

class Cat:
  def meow(self):
    print("Meow! 🐱")

  def sleep(self):
    print("The cat is sleeping. 😴")

cat = Cat()
cat.meow()
cat.sleep()

πŸ’‘ Call the methods in a different order.

Hero Class

class Hero:
  def moveUp(self):
    print("⬆️ Hero moves up")

  def moveDown(self):
    print("⬇️ Hero moves down")

hero = Hero()
hero.moveUp()
hero.moveDown()

πŸ’‘ Add moveLeft and moveRight methods.

Class with Say Function

class Robot:
  def say(self, words):
    print("πŸ€– Robot says:", words)

rob = Robot()
rob.say("Hello World")

πŸ’‘ Make the robot say your name.

Using Variables Inside a Class

class Car:
  def __init__(self, color):
    self.color = color

  def showColor(self):
    print("πŸš— The car color is", self.color)

myCar = Car("red")
myCar.showColor()

πŸ’‘ Change "red" to another color.

Class with Two Variables

class Student:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def introduce(self):
    print("Hi, my name is", self.name, "and I am", self.age, "years old.")

student1 = Student("Alice", 10)
student1.introduce()

πŸ’‘ Create another student with your name and age.

Add Method that Does Math

class Calculator:
  def add(self, a, b):
    print("Result:", a + b)

calc = Calculator()
calc.add(5, 3)

πŸ’‘ Add another function called subtract.

Favorite Food Class

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

  def eat(self, food):
    print(self.name, "is eating", food)

p = Person("John")
p.eat("pizza")

πŸ’‘ Change "pizza" to your favorite food.

Challenge – Hero Adventure

class Hero:
  def moveUp(self):
    print("⬆️ Hero moves up")

  def moveDown(self):
    print("⬇️ Hero moves down")

  def moveLeft(self):
    print("⬅️ Hero moves left")

  def moveRight(self):
    print("➑️ Hero moves right")

  def say(self, words):
    print("πŸ’¬ Hero says:", words)
player = Hero()
player.moveUp()
player.moveRight()
player.say("I found the treasure! πŸͺ™")

πŸ’‘ Task: Make the hero move in a square and then say "Mission Complete!"