Lesson 7 - Classes & Objects
Python Classes and Objects
Classes and Objects in Python:
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
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
def sound(self):
print("Some sound")
myAnimal = Animal()
myAnimal.sound()
π‘ Try changing "Some sound" to "Meow" or "Woof".
Dog Class
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
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
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
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
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
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
def add(self, a, b):
print("Result:", a + b)
calc = Calculator()
calc.add(5, 3)
π‘ Add another function called subtract.
Favorite Food Class
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
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!"