Skip to main content
Logo image

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

Section 1.5 Object-Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that models the world as a collection of interacting objects. An object is an instance of a class, which can represent almost anything.
Classes act as blueprints that define the structure and behavior of objects. A class specifies the attributes and methods of an object. - An attribute is a variable that stores information about the object. - A method is a function that interacts with or modifies the object. Although you can create custom classes, many useful classes are already available in Sage and Python, such as those for integers, lists, strings, and graphs.

Subsection 1.5.1 Objects in Sage

In Python and Sage, almost everything is an object. When assigning a value to a variable, the variable references an object. The type() function allows us to check an object’s class.
The output confirms that 'a' is an instance of the str (string) class, and vowels is an instance of the list class. We just created a list object named vowels by assigning a series of characters within the square brackets to a variable. The object vowels represents a list of string elements, and we can interact with it using various methods.

Subsection 1.5.2 Dot Notation and Methods

Dot notation is used to access an object’s attributes and methods. For example, the list class has an append() method that allows us to add elements to a list.
Here, 'y' is passed as a parameter to the append() method, adding it to the end of the list. The list class provides many other methods for interacting with lists.

Subsection 1.5.3 Sage’s Set Class

While list is a built-in Python class, Sage provides specialized classes for mathematical objects. One such class is Set, which we will explore later on in the next chapter.
The Set class in Sage provides attributes and methods specifically designed for working with sets.
While OOP might seem abstract at first, it will become clearer as we explore more and dive deeper into Sage features. Sage’s built-in classes offer a structured way to represent data and perform powerful mathematical operations. In the next chapters, we’ll see how Sage utilizes OOP principles and its built-in classes to perform mathematical operations.