Skip to content

Object-Oriented Programming

Classes and Objects

Python Object-Oriented Programming

Basic Class Definition

python
# Python - Basic class definition
class Person:
    """Human class"""

    # Class variable
    species = "Homo sapiens"

    def __init__(self, name, age):
        """Constructor"""
        self.name = name  # Instance variable
        self.age = age
        self._private_var = "private variable"  # Convention for private variable

    def introduce(self):
        """Self-introduction method"""
        return f"My name is {self.name}, and I am {self.age} years old"

    def have_birthday(self):
        """Birthday method"""
        self.age += 1
        return f"{self.name} had a birthday, now {self.age} years old"

    @property
    def is_adult(self):
        """Property method"""
        return self.age >= 18

    @classmethod
    def create_anonymous(cls):
        """Class method"""
        return cls("Anonymous", 0)

    @staticmethod
    def is_valid_age(age):
        """Static method"""
        return 0 <= age <= 150

# Create objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)

# Call methods
print(person1.introduce())  # My name is Alice, and I am 25 years old
print(person2.have_birthday())  # Bob had a birthday, now 31 years old
print(person1.is_adult)  # True

# Use class method
anonymous = Person.create_anonymous()
print(anonymous.introduce())  # My name is Anonymous, and I am 0 years old

# Use static method
print(Person.is_valid_age(200))  # False

Inheritance

python
# Python - Inheritance
class Student(Person):
    """Student class, inherits from Person"""

    def __init__(self, name, age, student_id, major):
        # Call parent class constructor
        super().__init__(name, age)
        self.student_id = student_id
        self.major = major
        self.grades = []

    def add_grade(self, grade):
        """Add a grade"""
        self.grades.append(grade)

    def get_average(self):
        """Calculate the average grade"""
        if not self.grades:
            return 0
        return sum(self.grades) / len(self.grades)

    def introduce(self):
        """Override parent class method"""
        base_intro = super().introduce()
        return f"{base_intro}, student ID {self.student_id}, major in {self.major}"

# Create a student object
student = Student("Charlie", 20, "2023001", "Computer Science")
student.add_grade(85)
student.add_grade(92)
student.add_grade(78)

print(student.introduce())  # My name is Charlie, and I am 20 years old, student ID 2023001, major in Computer Science
print(f"Average grade: {student.get_average():.1f}")  # Average grade: 85.0

Polymorphism and Abstract Classes

python
# Python - Polymorphism and abstract classes
from abc import ABC, abstractmethod

class Animal(ABC):
    """Abstract animal class"""

    def __init__(self, name):
        self.name = name

    @abstractmethod
    def make_sound(self):
        """Abstract method"""
        pass

    def introduce(self):
        return f"I am {self.name}"

class Dog(Animal):
    """Dog class"""

    def make_sound(self):
        return "Woof!"

    def fetch(self):
        return f"{self.name} is fetching the ball"

class Cat(Animal):
    """Cat class"""

    def make_sound(self):
        return "Meow!"

    def climb(self):
        return f"{self.name} is climbing a tree"

# Polymorphism example
animals = [Dog("Buddy"), Cat("Mimi")]

for animal in animals:
    print(f"{animal.introduce()}: {animal.make_sound()}")
    # I am Buddy: Woof!
    # I am Mimi: Meow!

Special Methods

python
# Python - Special methods
class Vector:
    """Vector class"""

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        """String representation"""
        return f"Vector({self.x}, {self.y})"

    def __repr__(self):
        """Detailed string representation"""
        return f"Vector(x={self.x}, y={self.y})"

    def __add__(self, other):
        """Addition operation"""
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        """Subtraction operation"""
        return Vector(self.x - other.x, self.y - other.y)

    def __eq__(self, other):
        """Equality comparison"""
        return self.x == other.x and self.y == other.y

    def __len__(self):
        """Length (magnitude)"""
        return int((self.x ** 2 + self.y ** 2) ** 0.5)

# Use special methods
v1 = Vector(3, 4)
v2 = Vector(1, 2)

print(v1)  # Vector(3, 4)
print(v1 + v2)  # Vector(4, 6)
print(v1 - v2)  # Vector(2, 2)
print(v1 == v2)  # False
print(len(v1))  # 5

JavaScript Object-Oriented Programming

Basic Class Definition

javascript
// JavaScript - Basic class definition
class Person {
  // Class variable (static property)
  static species = "Homo sapiens";

  constructor(name, age) {
    this.name = name; // Instance variable
    this.age = age;
    this._privateVar = "private variable"; // Convention for private variable
  }

  introduce() {
    return `My name is ${this.name}, and I am ${this.age} years old`;
  }

  haveBirthday() {
    this.age += 1;
    return `${this.name} had a birthday, now ${this.age} years old`;
  }

  // Getter property
  get isAdult() {
    return this.age >= 18;
  }

  // Static method
  static createAnonymous() {
    return new Person("Anonymous", 0);
  }

  static isValidAge(age) {
    return age >= 0 && age <= 150;
  }
}

// Create objects
const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);

// Call methods
console.log(person1.introduce()); // My name is Alice, and I am 25 years old
console.log(person2.haveBirthday()); // Bob had a birthday, now 31 years old
console.log(person1.isAdult); // true

// Use static method
const anonymous = Person.createAnonymous();
console.log(anonymous.introduce()); // My name is Anonymous, and I am 0 years old

// Use static method
console.log(Person.isValidAge(200)); // false

Inheritance

javascript
// JavaScript - Inheritance
class Student extends Person {
  constructor(name, age, studentId, major) {
    // Call parent class constructor
    super(name, age);
    this.studentId = studentId;
    this.major = major;
    this.grades = [];
  }

  addGrade(grade) {
    this.grades.push(grade);
  }

  getAverage() {
    if (this.grades.length === 0) {
      return 0;
    }
    return (
      this.grades.reduce((sum, grade) => sum + grade, 0) / this.grades.length
    );
  }

  introduce() {
    const baseIntro = super.introduce();
    return `${baseIntro}, student ID ${this.studentId}, major in ${this.major}`;
  }
}

// Create a student object
const student = new Student("Charlie", 20, "2023001", "Computer Science");
student.addGrade(85);
student.addGrade(92);
student.addGrade(78);

console.log(student.introduce()); // My name is Charlie, and I am 20 years old, student ID 2023001, major in Computer Science
console.log(`Average grade: ${student.getAverage().toFixed(1)}`); // Average grade: 85.0

Polymorphism

javascript
// JavaScript - Polymorphism
class Animal {
  constructor(name) {
    this.name = name;
  }

  makeSound() {
    throw new Error("Abstract method 'makeSound' must be implemented");
  }

  introduce() {
    return `I am ${this.name}`;
  }
}

class Dog extends Animal {
  makeSound() {
    return "Woof!";
  }

  fetch() {
    return `${this.name} is fetching the ball`;
  }
}

class Cat extends Animal {
  makeSound() {
    return "Meow!";
  }

  climb() {
    return `${this.name} is climbing a tree`;
  }
}

// Polymorphism example
const animals = [new Dog("Buddy"), new Cat("Mimi")];

animals.forEach((animal) => {
  console.log(`${animal.introduce()}: ${animal.makeSound()}`);
});
// I am Buddy: Woof!
// I am Mimi: Meow!

Comparison

FeaturePythonJavaScript
Class Definitionclass MyClass:class MyClass {}
Constructor__init__(self, ...)constructor(...)
Instance Methoddef method(self, ...)method(...) {}
Inheritanceclass Child(Parent):class Child extends Parent
Call Parent Methodsuper().method()super.method()
Static Method@staticmethodstatic method() {}
Class Method@classmethodNot directly supported
Property/Getter@propertyget prop() {}
Private Variable_var (convention)#var (ES2022)
Abstract Classabc moduleNo native support (frameworks)

Summary

  • Python: Mature OOP system, clear syntax, supports multiple inheritance.
  • JavaScript: Prototype-based, class is syntactic sugar, single inheritance.

Exercises

  1. Create a Car class with properties and methods.
  2. Create a ElectricCar class that inherits from Car.
  3. Implement polymorphism with different shape classes.

Next Steps

Now you know about OOP. Next, we'll learn about exception handling.