Creating Objects
Think of an object as a real thing created from a blueprint (class). Imagine:
- A class is a blueprint for making cookies.
- An object is an actual cookie you bake using the blueprint.
In Python, when we create an object, we are baking a "cookie" from the "blueprint" of a class.
How do we create objects?
To create an object, you simply call the class like a function. For example:
class Dog:
def __init__(self, name, breed): # Constructor
self.name = name
self.breed = breed
# Create an object
my_dog = Dog("Buddy", "Golden Retriever")
What’s happening here:
is the class (the blueprint).Dog
is the object (a specific dog we created using the class).my_dog
andBuddy are passed as values to theGolden Retriever
method, which initializes the object.__init__
Accessing attributes
Attributes are like the details of an object. For example:
- A dog's name and breed are its attributes. You can access them using the dot
operator:.
# Accessing the attributes of the object
print(my_dog.name) # Output: Buddy
print(my_dog.breed) # Output: Golden Retriever
Here’s how it works:
: This asks Python to give themy_dog.name name
of the object.my_dog
: This asks Python to give themy_dog.breed breed
of the object.my_dog
Using methods
Methods are like the actions an object can perform. For example:
- A dog can bark. We define methods in the class and call them using the object:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self): # Method: an action the object can do
return f"{self.name} says Woof!"
# Create an object
my_dog = Dog("Buddy", "Golden Retriever")
# Call the method
print(my_dog.bark()) # Output: Buddy says Woof!
What’s happening here:
is a method defined in the class.bark() - When we call
, it runs themy_dog.bark()
bark
method for themy_dog
object. - Inside the method,
refers to the specific dog’s name.self.name
Putting it all together
Here’s a full example:
class Car:
def __init__(self, brand, color):
self.brand = brand # Attribute: Car brand
self.color = color # Attribute: Car color
def start(self): # Method: Action to start the car
return f"The {self.color} {self.brand} is starting!"
# Create objects
car1 = Car("Toyota", "red")
car2 = Car("Tesla", "blue")
# Access attributes
print(car1.brand) # Output: Toyota
print(car2.color) # Output: blue
# Call methods
print(car1.start()) # Output: The red Toyota is starting!
print(car2.start()) # Output: The blue Tesla is starting!
Key points to remember
-
Objects are created from classes, like a real-world thing from a blueprint.
- Use the dot
to:.
- Access attributes (details about the object).
- Call methods (actions the object can perform).
- Methods are like functions inside a class that describe what the object can do.