Table of Contents

, , , , , , , , ,

About the Club

Python Club Topics - Classes & Objects

Questions

  1. What a class? A class is like a blueprint or template for creating objects. It defines the attributes (data) and methods (actions) that objects of that class will have. It is a logical entity and doesn't occupy memory space when declared.
  2. What an object? An object is an instance of a class. It's a concrete entity that exists in memory and has specific values for the attributes defined by its class. It's a physical entity that can be manipulated.

Class

  1. A class is a blueprint for creating objects

Class examples

  1. Define a basic class
    class Dog:
        def __init__(self, name, breed):
            self.name = name
            self.breed = breed
     
    # Create an instance of the Dog class
    my_dog = Dog("Buddy", "Golden Retriever")
     
    # Access the attributes of the object
    print(my_dog.name)
    print(my_dog.breed)
  2. You cannot print an object directly like a list, tuple, or dictionary
    class Dog:
        def __init__(self, name, breed):
            self.name = name
            self.breed = breed
     
    # Create an instance of the Dog class
    my_dog = Dog("Buddy", "Golden Retriever")
     
    # Access the attributes of the object
    print(my_dog)
  3. Instead, you print all values of an object with the _ _dict_ _ method
    class Dog:
        def __init__(self, name, breed):
            self.name = name
            self.breed = breed
     
    # Create an instance of the Dog class
    my_dog = Dog("Buddy", "Golden Retriever")
    print(my_dog.__dict__)