Book Image

Learning Object-Oriented Programming

By : Gaston C. Hillar
Book Image

Learning Object-Oriented Programming

By: Gaston C. Hillar

Overview of this book

Table of Contents (16 chapters)
Learning Object-Oriented Programming
About the Author
About the Reviewers

Customizing constructors in Python

We want to initialize instances of the Rectangle class with the values of both width and height. After we create an instance of a class, Python automatically calls the __init__ method. Thus, we can use this method to receive both the width and height arguments. We can then use these arguments to initialize attributes with the same names. We can think of the __init__ method as the equivalent of a constructor in other object-oriented programming languages.

The following lines create a Rectangle class and declare an __init__ method within the body of the class:

class Rectangle:
    def __init__(self, width, height):
        print("I'm initializing a new Rectangle instance.")
        self.width = width
        self.height = height

This method receives three arguments: self, width, and height. The first argument is a reference to the instance that called the method. We used the name self for this argument. It is important to notice that self is not a Python keyword...