Object Oriented Programming and classes
Comparison between JavaScript and Python
The information comes from the Udemy course "Become an AI Engineer: Python for JavaScript Developers" by Vilva Athiban
| Feature |
JavaScript |
Python |
| classes |
class Book {
constructor(title) {
this.title = title;
this.available = true;
}
describe() {
return `${this.title} is the title of the book`;
}
borrow() {
this.available = false;
}
// static method
static isEven(number) {
return number % 2 === 0;
}
}
const book = new Book("new title");
console.log(book.describe());
book.borrow();
console.log(book.available); // false
console.log(Book.isEven(4)); // true
|
class Book:
def __init__(self, title): # constructor
self.title = title
self.available = True # capital True
def describe(self): # every method gets `self` first
return f"{self.title} is the title of the book"
def borrow(self):
self.available = False
@staticmethod
def is_even(number): # no self
return number % 2 == 0
book = Book("new title") # no `new` keyword
print(book.describe())
book.borrow()
print(book.available) # False
print(Book.is_even(4)) # True
|
| Inheritance |
class BookDetails extends Book {
constructor(title, author) {
super(title); // pass args to parent
this.author = author;
}
printDetails() {
return `${this.title} is written by ${this.author}`;
}
}
const bd = new BookDetails("light bulb", "Edison");
console.log(bd.printDetails());
// "light bulb is written by Edison"
|
pass the parent as an argument to the classclass BookDetails(Book):
def __init__(self, title, author):
super().__init__(title) # super() takes NO args itself;
# call __init__ on it
self.author = author
def print_details(self):
return f"{self.title} is written by {self.author}"
bd = BookDetails("light bulb", "Edison")
print(bd.print_details()) # "light bulb is written by Edison"
# For JS devs: the two things that feel weird at first are
# (1) passing `self`
# to every method and
# (2) __init__ as the constructor name.
# Everything else maps 1:1.
|