Python Classes/Objects 🏗️
The Blueprint
A Class is like an object constructor, or a "blueprint" for creating objects. An Object is an instance of a class.
🍪 Analogy: The Cookie Cutter
Think of a Class as a Cookie Cutter.
- It defines the shape and size (properties/methods).
- You can't eat the cutter itself.
Think of an Object as the Cookie.
- You create it using the cutter.
- You can make as many cookies as you want from one cutter.
- Each cookie can have different decorations (property values like sprinkles vs frosting), but they all share the same structure.
✨ The __init__() Function
All classes have a function called __init__(), which is always executed when the class is being initiated. Use it to assign values to object properties.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name) # John
print(p1.age) # 36Note: The __init__() function is called automatically every time the class is being used to create a new object.
📝 The __str__() Function
The __str__() function controls what should be returned when the class object is represented as a string.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
p1 = Person("John", 36)
print(p1) # Output: John (36)👉 The self Parameter
The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of any function in the class.
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()🎯 Real-World Application: Game Characters
In a video game, you might have a Enemy class.
class Enemy:
def __init__(self, type, health):
self.type = type
self.health = health
def take_damage(self, amount):
self.health -= amount
print(f"{self.type} took {amount} damage! Health: {self.health}")
# Spawning enemies from the same blueprint
goblin = Enemy("Goblin", 100)
orc = Enemy("Orc", 200)
goblin.take_damage(10)💡 Class vs Instance Variables
Instance variables are for data unique to each instance, while class variables are for attributes and methods shared by all instances of the class.
class Dog:
kind = 'canine' # class variable shared by all dogs
def __init__(self, name):
self.name = name # instance variable unique to each instance
d = Dog('Fido')
e = Dog('Buddy')
print(d.kind) # canine
print(e.kind) # canine
print(d.name) # Fido
print(e.name) # Buddy