Learn Python this summer Day 11: Classes and Objects

Learn Python this summer Day 11: Classes and Objects

Welcome back! Yesterday, we learned about dictionaries and sets in Python. Today, we’ll dive into classes and objects, which are the foundation of object-oriented programming (OOP). By the end of this day, you’ll know how to create and use classes and objects in Python. Let’s get started!

What are Classes and Objects?

Classes: Templates for creating objects. They define the properties and behaviors that the objects created from the class will have.
Objects: Instances of classes. They represent specific examples of the class.
Creating a Class
You can define a class using the class keyword followed by the class name and a colon. Inside the class, you can define attributes and methods.

class Dog:
    # Class attribute
    species = "Canis familiaris"

    # Initializer / Instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def description(self):
        return f"{self.name} is {self.age} years old"

    # Another instance method
    def speak(self, sound):
        return f"{self.name} says {sound}"

Creating an Object

You can create an object (an instance of a class) by calling the class as if it were a function:

# Creating an instance of the Dog class
my_dog = Dog("Buddy", 3)

print(my_dog.name)       # Output: Buddy
print(my_dog.age)        # Output: 3
print(my_dog.species)    # Output: Canis familiaris

print(my_dog.description())  # Output: Buddy is 3 years old
print(my_dog.speak("Woof"))  # Output: Buddy says Woof

Class and Instance Attributes

Class Attributes: Shared by all instances of the class. Defined outside the init method.
Instance Attributes: Unique to each instance. Defined inside the init method.

Methods

Methods are functions defined inside a class that describe the behaviors of the objects. The first parameter of a method is always self, which refers to the instance calling the method.

Inheritance

Inheritance allows you to create a new class based on an existing class. The new class (child class) inherits attributes and methods from the existing class (parent class).

Example:

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

    def description(self):
        return f"{self.name} is {self.age} years old"

    def speak(self, sound):
        return f"{self.name} says {sound}"

# Inheriting from the Dog class
class Bulldog(Dog):
    def run(self, speed):
        return f"{self.name} runs {speed}!"

my_bulldog = Bulldog("Rocky", 5)
print(my_bulldog.description())  # Output: Rocky is 5 years old
print(my_bulldog.speak("Woof"))  # Output: Rocky says Woof
print(my_bulldog.run("slowly"))  # Output: Rocky runs slowly!

Practice Time!

Let’s put what we’ve learned into practice. Write a Python program that defines a class, creates objects, and demonstrates inheritance.

# Defining the Vehicle class
class Vehicle:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def description(self):
        return f"{self.year} {self.make} {self.model}"

# Defining the Car class that inherits from Vehicle
class Car(Vehicle):
    def __init__(self, make, model, year, doors):
        super().__init__(make, model, year)
        self.doors = doors

    def car_description(self):
        return f"{self.description()} with {self.doors} doors"

# Creating an instance of the Car class
my_car = Car("Toyota", "Camry", 2020, 4)

# Using methods from both Vehicle and Car classes
print(my_car.description())      # Output: 2020 Toyota Camry
print(my_car.car_description())  # Output: 2020 Toyota Camry with 4 doors

Conclusion

Great job today! You’ve learned how to create and use classes and objects in Python, which are fundamental concepts in object-oriented programming. Tomorrow, we’ll dive into inheritance and polymorphism, which will help you create more flexible and reusable code. Keep practicing and having fun coding!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *