Introduction to object-oriented programming

Programming – Session 4

  • What is a programming paradigm?
  • Basic object-oriented concepts

What is a programming paradigm?

Definitions

Programming paradigm

A method or style of programming that defines a set of principles, techniques, and patterns for structuring code to solve problems on a computer.

Procedural paradigm

  • Many paradigms exist (procedural, functional, logic…)
  • Till now in the course: procedural programming and modularity
    • Functions creation in modules and reutilization with import statements
    • But nothing stated about data. Where to define them?

What is a programming paradigm?

Object-Oriented Programming

Definition

A programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods).

Remarks

  • Attributes and methods that manipulate them are grouped in the same entity (objects)
  • In OOP, a computer program is designed as objects that interact with one another to implement functionnalities.

Basic object-oriented concepts

Objects, attributs and methods

Basic object-oriented concepts

Classes, instanciation constructors

  • A class defines the structure (attributes) and behavior (methods) of a family of objects. It consists of :

    • a name,
    • attributes (their name and, if applicable, their type),
    • methods (their name, return type, name and, if applicable, type of each argument, and their code),
    • constructor, a particular method called when an object is created and which role is to initialize the object attributes
  • An object is created from a class

Basic object-oriented concepts

Classes, instanciation, constructors

Class creation

class Person:
    """ Represents a person with a name, firstname, age, and city."""

    def __init__(self, name: str, firstname: str, age: int, city: str) -> None: # The constructor
        """ Constructs a new Person object with the specified name, firstname, age, and city."""
        self.name: str = name
        self.firstname: str = firstname
        self.age: int = age
        self.city: str = city

    def to_string(self) -> str:
        """ Returns a string representation of the person. """
        return f"{self.firstname} {self.name} ({self.age} old, from {self.city})"

Class instantiation (object creation)

if __name__ == '__main__':
  # Create a person named Alice Weber from London and 33 years old
  one_person = Person("Weber", "Alice", 33, "London")
  print(one_person.to_string())

  # Create a person named Bob Smith from Brighton and 25 years old
  a_second_person = Person("Smith", "Bob", 25, "Brighton")
  print(a_second_person.to_string())

Basic object-oriented concepts

Encapsulation

Definition

The principle of hiding or protecting (part of) the state of an object so that it cannot be accessed from outside the class.

  • Attribute city is by convention private to objects Person
class Person:
    """
    Represents a person with a name, firstname, age, and city.
    """
    def __init__(self, name: str, firstname: str, age: int, city: str) -> None: # The constructor
        """
        Constructs a new Person object with the specified name, firstname, and city.
        """
        self.name: str = name
        self.firstname: str = firstname
        self.age: int = age
        self._city: str = city

    def to_string(self) -> str:
        """ Returns a string representation of the person."""

        return f"{self.firstname} {self.name} ({self.age} old, from {self._city})"

if __name__ == '__main__':
    one_person = Person("Weber", "Alice", 33, "London")
    print(one_person.name) # No error. Expected output: "Weber"
    print(one_person._city) # No error. Expected output: "London"

Basic object-oriented concepts

Inheritance

Definition

A way of structuring code that defines hierarchical relationships between classes.

from person import Person

class Student(Person):
    """Represents a student of IMT Atlantique."""

    # It is good practice to also call the parent's constructor
    # Then you can complement with additional codes if needed
    def __init__(self, studentid: int, name: str, firstname: str, age: int, city: str) -> None:  # The constructor
        """Constructs a new student object with the specified studentid, name, firstname, age, and city."""

        super().__init__(name, firstname, age, city)  # Call parent's constructor
        self._studentid: int = studentid
        self._courses: list[str] = []

    def to_string(self) -> str:
        """Returns a string representation of the person."""

        return (
            f"{self._studentid}, " + super().to_string() + ". Enrolled in " + str(self._courses)
        )

    def enroll_in_course(self, course_name):
        """Add the course_name in the list of courses of the student."""

        if course_name not in self._courses:
            self._courses.append(course_name)


if __name__ == "__main__":
    one_student = Student(1234, "Weber", "Alice", 33, "London")
    print(
        one_student.to_string()
    )  # Expected output: "1234, Alice Weber (33 old, from London). Enrolled in []"

    one_student.enroll_in_course("UE Informatique")
    print(
        one_student.to_string()
    )  # Expected output: "1234, Alice Weber (33 old, from London). Enrolled in [UE Informatique]"

Recap of the session

What’s next?

Practical activity (~2h30)

Implement your first OO programs

  • Create and instanciate classes
  • Write and execute OO programs

After the session

  • Review the articles of the session
  • Check your understanding with the quiz
  • Complete the non-optional practical activity
  • Check next session’s “Before the class” section