Free Coding Tutorials: Mastering Python Fundamentals – Part 9

Delphi

Chapter 9: Objects and Classes

Objects and classes are fundamental concepts in Mastering Python Fundamentals, in Mastering Python Fundamentals, and most object-oriented programming (OOP) languages. They allow you to model real-world entities and concepts within your code. This chapter will guide you through the basics of objects and classes, helping you understand how to create and use them in your Python programs.

9.1 Introduction to Objects and Classes

In Python, everything is an object, and every object belongs to a class. A class can be thought of as a blueprint for creating objects (instances). An object is an instance of a class, containing data (attributes) and behavior (methods).

9.1.1 Defining a Class

A class is defined using the class keyword, followed by the class name and a colon. Inside the class, you can define attributes and methods.

Example: Defining a Simple Class

class Dog:
    # Class attribute
    species = 'Canis familiaris'

    # Initializer / Instance Attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method
    def bark(self):
        return f"{self.name} says woof!"

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as dog_class.py.
  4. The Dog class has two instance attributes (name and age) and one instance method (bark).

9.1.2 Creating an Object

Once you’ve defined a class, you can create objects (instances) of that class.

Example: Creating an Object

# Creating instances of the Dog class
my_dog = Dog("Rex", 5)

# Accessing attributes
print(f"My dog's name is {my_dog.name} and he is {my_dog.age} years old.")

# Calling methods
print(my_dog.bark())

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as create_dog_object.py.
  4. Run the program by typing:
   python create_dog_object.py
  1. The output will display:
   My dog's name is Rex and he is 5 years old.
   Rex says woof!

9.2 The __init__ Method

The __init__ method is a special method in Python classes. It’s called the constructor and is automatically invoked when you create a new instance of a class. It is used to initialize the object’s attributes.

9.2.1 Example of Using __init__

Example: Initializing an Object

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def description(self):
        return f"{self.year} {self.make} {self.model}"

# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla", 2020)
print(my_car.description())

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as car_class.py.
  4. Run the program by typing:
   python car_class.py
  1. The output will display:
   2020 Toyota Corolla

9.3 Instance vs. Class Attributes

Instance attributes are unique to each instance, while class attributes are shared among all instances of the class.

9.3.1 Example of Instance Attributes

Example: Unique Attributes

class Dog:
    species = 'Canis familiaris'

    def __init__(self, name, age):
        self.name = name
        self.age = age

dog1 = Dog("Buddy", 3)
dog2 = Dog("Milo", 2)

print(dog1.name)  # Outputs: Buddy
print(dog2.name)  # Outputs: Milo

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as instance_attributes.py.
  4. Run the program by typing:
   python instance_attributes.py
  1. The output will display:
   Buddy
   Milo

9.3.2 Example of Class Attributes

Example: Shared Attributes

class Dog:
    species = 'Canis familiaris'

    def __init__(self, name, age):
        self.name = name
        self.age = age

dog1 = Dog("Buddy", 3)
dog2 = Dog("Milo", 2)

print(dog1.species)  # Outputs: Canis familiaris
print(dog2.species)  # Outputs: Canis familiaris

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as class_attributes.py.
  4. Run the program by typing:
   python class_attributes.py
  1. The output will display:
   Canis familiaris
   Canis familiaris

9.4 Methods in Classes

Methods are functions that belong to an object. They can manipulate the object’s attributes or perform actions.

9.4.1 Defining and Using Methods

Example: Method to Calculate Dog’s Age in Human Years

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def dog_years(self):
        return self.age * 7

# Creating an instance of Dog
my_dog = Dog("Buddy", 3)
print(f"My dog is {my_dog.dog_years()} human years old.")

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as dog_years_method.py.
  4. Run the program by typing:
   python dog_years_method.py
  1. The output will display:
   My dog is 21 human years old.

9.5 Inheritance

Inheritance allows a class (child class) to inherit attributes and methods from another class (parent class). This promotes code reusability and organization.

9.5.1 Creating a Child Class

Example: Inheriting from a Parent Class

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def speak(self):
        return f"{self.name} makes a sound."

class Dog(Animal):
    def __init__(self, name, age):
        super().__init__(name, 'Canis familiaris')
        self.age = age

    def speak(self):
        return f"{self.name} barks."

# Creating an instance of Dog
my_dog = Dog("Buddy", 3)
print(my_dog.speak())

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as inheritance.py.
  4. Run the program by typing:
   python inheritance.py
  1. The output will display:
   Buddy barks.

9.6 Polymorphism

Polymorphism allows methods to be used in different ways depending on the object that is invoking them. The same method name can be used for different classes.

9.6.1 Example of Polymorphism

Example: Polymorphism with Speak Method

class Cat:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} meows."

class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} barks."

# Using polymorphism
animals = [Cat("Whiskers"), Dog("Buddy")]

for animal in animals:
    print(animal.speak())

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as polymorphism.py.
  4. Run the program by typing:
   python polymorphism.py
  1. The output will display:
   Whiskers meows.
   Buddy barks.

9.7 Operator Overloading

Operator overloading allows you to define the behavior of operators (+, -, *, etc.) for custom objects.

9.7.1 Overloading the + Operator

Example: Adding Two Objects

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

# Creating instances of Point
point1 = Point(1, 2)
point2 = Point(3, 4)
point3 = point1 + point2

print(point3)  # Outputs

: (4, 6)

Step-by-Step Guide:

  1. Open your text editor.
  2. Type the code above into your editor.
  3. Save the file as operator_overloading.py.
  4. Run the program by typing:
   python operator_overloading.py
  1. The output will display:
   (4, 6)

Conclusion

Objects and classes are the building blocks of object-oriented programming in Python. This chapter has covered the essentials, including creating classes, working with attributes and methods, and implementing OOP principles like inheritance, polymorphism, and operator overloading. By mastering these concepts, you can design more complex and organized programs, making your code easier to understand, maintain, and expand. Keep practicing with real-world examples to strengthen your understanding!

Latest Posts