Python Basics 3
Python
Basics
This post is exploring the basics of Python
This is a test.
Explanation:
class Pet:: We define ourPetclass, the blueprint for creating different types of pets. Think of this like a template.- This creates a new class named “Pet”
def __init__(self, name, species, age):The__init__method is our special constructor!- It’s the main function that gets called automatically when you create an object (an instance) of this
Petclass:self: We useselfto reference the individual pet object. This way we can access and modify the attributes like a name, species, age within the constructor.
- It’s the main function that gets called automatically when you create an object (an instance) of this
self.name = nameand similar lines - These lines assign values to each of our pet’s properties:- Each
attribute(likename,species,age) gets set for a specificPetinstance.
- Each
def make_sound(self):This is a method - it describes how we will interact with this object.- When you call
make_sound()on ourpet1, it prints the sound the pet makes!
- When you call
- Creating Objects (
pet1,pet2)- We create two instances of our
Petclass, each representing a different animal:pet1 = Pet("Fluffy", "Cat", 3): This creates an instance calledpet1for a cat named “Fluffy” that’s 3 years old.pet2 = Pet("Max", "Dog", 5): This creates another instance,pet2, for a dog named “Max”.
- We create two instances of our
- Using Object Properties
- We print the name, species, and age of each pet object using string formatting, which helps us to display them in a clear way using f-strings (like
f"{pet1.name}...).
- We print the name, species, and age of each pet object using string formatting, which helps us to display them in a clear way using f-strings (like
Summary:
This example highlights: - We define class blueprints for different pets. - The constructor (__init__) sets up initial attributes of each pet instance. - Methods (functions within the class) give the objects ways to interact with us and their own “actions” (like making a sound).