Once Alex had mastered the basics of Python, he began to explore more advanced topics. One day, he stumbled upon the concept of object-oriented programming and the use of classes and objects in Python. Alex was intrigued and decided to learn more.
He started by creating a simple class for a Car object, with attributes such as make, model, year, and color. He also included a method to display information about the car.
class Car: def __init__(self, make, model, year, color): self.make = make self.model = model self.year = year self.color = color def display_car_info(self): print(f"This is a {self.color} {self.make} {self.model} from {self.year}.")
ext, Alex created an instance of the Car class and assigned values to its attributes:
my_car = Car("Toyota", "Corolla", 2020, "blue")
He then called the display_car_info() method on the my_car object:
my_car.display_car_info()
The output was:
This is a blue Toyota Corolla from 2020.
Alex was excited to see that he could create objects with their own attributes and methods, and use them to perform specific tasks.
He decided to create another class, this time for a Dog object. The Dog class had attributes such as name, breed, and age, and a method to bark.
class Dog: def __init__(self, name, breed, age): self.name = name self.breed = breed self.age = age def bark(self): print(f"{self.name} barks!")
Alex then created an instance of the Dog class and assigned values to its attributes:
my_dog = Dog("Fido", "Labrador Retriever", 3)
He called the bark() method on the my_dog object:
my_dog.bark()
The output was:
Fido barks!
Alex was thrilled to see that he could create multiple classes with their own attributes and methods, and use them in different ways.
He continued to explore more advanced topics in Python, but the concept of classes and objects remained one of his favorites. He knew that he could use them to create more complex programs and solve more intricate problems.