Classes and Objects
Learn the core principles of object-oriented programming in Python and JavaScript, including classes, objects, data members, constructors, and access modifiers.
We'll cover the following...
In both JavaScript and Python, classes and objects are foundational to object-oriented programming (OOP). They help in organizing code, making it reusable, and modular by encapsulating data and behavior within cohesive blocks.
Classes
In Python, a class serves as a blueprint for creating objects (instances). It encapsulates data (attributes) and behavior (methods) related to those objects. Classes are defined using the class
keyword, followed by the class name and a colon (:
). They can contain attributes and methods.
class Car:# Constructordef __init__(self, make, model):self.make = makeself.model = model# Method to display car detailsdef display_info(self):print("Make:", self.make)print("Model:", self.model)# Creating an object of the Car classmy_car = Car("Toyota", "Camry")my_car.display_info()
In JavaScript, a class also serves as a blueprint for creating objects. It defines object properties (fields) and behaviors (methods). Classes in JavaScript are declared using the class
keyword followed by the class name. They can contain constructors, methods, and instance variables.
class Car {// Constructorconstructor(make, model) {this.make = make;this.model = model;}// Method to display car detailsdisplayInfo() {console.log("Make: " + this.make);console.log("Model: " + this.model);}}// Create an instance of the Car classconst myCar = new Car("Toyota", "Corolla");// Call the displayInfo method to display the car detailsmyCar.displayInfo();
Differences between Python and JavaScript classes:
Syntax: Python uses indentation to define the scope of classes and methods, whereas JavaScript uses curly braces
{}
.Constructor: In Python, the constructor is defined using the
__init__
method, while in JavaScript, it is defined using theconstructor
method.Access modifiers: JavaScript classes do not have built-in access modifiers like
public
,protected
, orprivate
(though private fields can be simulated with the#
syntax), ...