Skip to main content

Discrete Math with SageMath: Learn math with open-source software

Section 1.3 Object-Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that models the world as a collection of interacting objects. More specifically, an object is an instance of a class. A class can represent almost anything.
Classes are like blueprints that define the structure and behavior of objects. A class defines the attributes and methods of an object. An attribute is a variable that stores information about the object. A method is a function that can interact with or modify the object. Although you can create custom classes, the open-source community has already defined classes for us. For example, there are specialized classes for working with integers, lists, strings, graphs, and more.
In Python and Sage, almost everything is an object. When assigning a value to a variable, the variable references an object. In this case, the object is a list of strings.
The type() function confirms that 'a' is an instance of the string class and vowels is an instance of the list class. We create a list object named vowels by assigning a series of characters within square brackets to a variable. This object, vowels, now represents a list of string elements, and we can interact with it using various methods.
Dot notation is a syntax used to access an object’s attributes and call an object’s methods. For example, the list class has an append method, allowing us to add elements to the list.
A parameter is a variable passed to a method. In this case, the parameter is the string 'y'. The append method adds the string 'y' to the end of the list. The list class has many more methods that we can use to interact with the list object. While list is a built-in Python class, Sage offers many more classes specialized for mathematical applications. For example, we will learn about the Sage Set class in the next chapter. Objects instantiated from the Set class have methods and attributes useful for working with sets.
While OOP might seem abstract at first, it will become clearer as we dive deeper into Sage. We will see how Sage utilizes OOP principles and built-in classes to offer a structured way to represent data and perform powerful mathematical operations.