Python Basics 3

Python
Basics
This post is exploring the basics of Python
Author

Quantilogy

Published

January 20, 2024

This is a test.

Explanation:

  1. class Pet:: We define our Pet class, the blueprint for creating different types of pets. Think of this like a template.
    • This creates a new class named “Pet”
  2. 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 Pet class:
      • self: We use self to reference the individual pet object. This way we can access and modify the attributes like a name, species, age within the constructor.
  3. self.name = name and similar lines - These lines assign values to each of our pet’s properties:
    • Each attribute (like name, species, age) gets set for a specific Pet instance.
  4. def make_sound(self): This is a method - it describes how we will interact with this object.
    • When you call make_sound() on our pet1, it prints the sound the pet makes!
  5. Creating Objects (pet1, pet2)
    • We create two instances of our Pet class, each representing a different animal:
      • pet1 = Pet("Fluffy", "Cat", 3): This creates an instance called pet1 for a cat named “Fluffy” that’s 3 years old.
      • pet2 = Pet("Max", "Dog", 5): This creates another instance, pet2, for a dog named “Max”.
  6. 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}...).

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).


Support my work with a coffee