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
    • Fosters program modularity and ease of code reuse and maintenance for small programs
    • Not well-suited for “complex problems” (automatic games, understanding and translating natural languages, decision support, graphical programs, etc)

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): # The constructor
    """
        Constructs a new Person object with the specified name, firstname, age, and city.
    """
        self.name = name
        self.firstname = firstname
        self.age = age
        self.city = 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.

  • Attributes age and city are 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): # The constructor
    """
        Constructs a new Person object with the specified name, firstname, age, and city.
    """
        self.name = name
        self.firstname = firstname
        self.__age = age
        self._city = 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"
        print(one_person.__age) # Raises an error: AttributeError: 'Person' object has no attribute '__age'
        print(one_person._Person__age) # No error. Expected output: 33

Basic object-oriented concepts

Inheritance

Definition

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

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
    # It is also good practice not to repeat arguments of the parent class
    # Arguments *args and **kwargs are here for this purpose
    def __init__(self, studentid: int, name: str, firstname: str, age: int, city: str): # The constructor
    """
        Constructs a new student object with the specified studentid, name, firstname, age, city.
    """
        super().__init__(*args, **kwargs) # 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 " + 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 __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