Defining Classes
A class is like a blueprint or recipe. Imagine you’re designing a blueprint for a house. The blueprint describes what the house should look like, but the actual house doesn’t exist yet. In Python:
- A class is the blueprint.
- An object is the actual house built from the blueprint.
How do you define a class?
You create a class in Python using the class
keyword. Here's a basic example:
class House:
pass
This creates a blueprint for a "House," but it doesn’t do anything yet. The pass
keyword is just a placeholder when you’re not adding anything right away.
The __init__
method (Constructor)
__init__
The __init__
- When you build a house, you need to decide its color, number of rooms, etc.
- The
method lets you set these details when creating an object.__init__
Example: a simple class
Let’s create a House
class where each house has a color and a number of rooms:
class House:
def __init__(self, color, rooms): # The constructor
self.color = color # Attribute for color
self.rooms = rooms # Attribute for number of rooms
Here’s what happens:
is the constructor. It takes two pieces of information: the house’s color and number of rooms.def __init__(self, color, rooms)
andself.color = color store this information in the object.self.rooms = rooms
Creating an object (an instance of a class)
Now let’s use the House
blueprint to create an actual house:
# Creating a house object
my_house = House("blue", 3)
# Accessing attributes
print(my_house.color) # Output: blue
print(my_house.rooms) # Output: 3
Explanation:
creates a house object with a blue color and 3 rooms.my_house = House("blue", 3) - You can access the
andcolor
attributes using the dot (rooms
.
) notation.
Why use the __init__
method?
__init__
Without the __init__
my_house = House()
my_house.color = "blue"
my_house.rooms = 3
The __init__
Complete example
Here’s a fun and complete example to practice:
class Dog:
def __init__(self, name, breed): # Constructor
self.name = name # Store dog's name
self.breed = breed # Store dog's breed
def bark(self): # A method to make the dog bark
return f"{self.name} says Woof!"
# Creating a dog object
my_dog = Dog("Buddy", "Golden Retriever")
# Accessing attributes and methods
print(my_dog.name) # Output: Buddy
print(my_dog.breed) # Output: Golden Retriever
print(my_dog.bark()) # Output: Buddy says Woof!
Key points to remember:
- Classes are blueprints, and objects are actual things created from the blueprint.
- The
method initializes the object with the values you provide.__init__
- Use
to refer to the object being created or modified.self