Now that we've introduced the core concepts of Object-Oriented Programming (OOP) – classes and objects – let's bring them to life with a practical and simple example. We'll create a Dog class, which is a blueprint for representing different dog objects. Each dog will have its own characteristics (attributes) and behaviors (methods).
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
self.is_hungry = True
def bark(self):
return "Woof! Woof!"
def eat(self):
if self.is_hungry:
self.is_hungry = False
return f"{self.name} is eating."
else:
return f"{self.name} is not hungry right now."In this Dog class:
class Dog:: This line defines our blueprint for creatingDogobjects.def __init__(self, name, breed):: This is the constructor method. It's called automatically when you create a newDogobject.selfrefers to the instance of the class being created.nameandbreedare parameters we pass in to customize each dog. Inside__init__, we set up the initial state of the dog object by assigning values to its attributes:self.name,self.breed, andself.is_hungry(which defaults toTruefor a new dog).def bark(self):: This is a method that defines a behavior for ourDogobjects. When called, it returns the string "Woof! Woof!".def eat(self):: This method also defines a behavior. It checks if the dogis_hungry. If it is, it setsis_hungrytoFalseand returns a message indicating the dog is eating. Otherwise, it informs that the dog isn't hungry.
Now, let's create some actual Dog objects (instances) from our Dog class and see them in action:
my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Lucy", "Poodle")
print(f"My dog's name is {my_dog.name} and he is a {my_dog.breed}.")
print(f"Your dog's name is {your_dog.name} and she is a {your_dog.breed}.")
print(my_dog.bark())
print(your_dog.eat())
print(your_dog.eat()) # Trying to eat againIn this code:
my_dog = Dog("Buddy", "Golden Retriever"): We're creating an object namedmy_dogfrom theDogclass. We pass "Buddy" and "Golden Retriever" to the__init__method, which sets up thenameandbreedfor this specificDogobject.your_dog = Dog("Lucy", "Poodle"): Similarly, we create anotherDogobject namedyour_dog.print(f"My dog's name is {my_dog.name}..."): We access the attributes of our objects using dot notation (e.g.,my_dog.name).print(my_dog.bark()): We call thebarkmethod on themy_dogobject.print(your_dog.eat()): We call theeatmethod. The first time,Lucyis hungry, so she eats.print(your_dog.eat()): The second time we calleatonyour_dog, she's no longer hungry, and the method reflects that.