Classes and OOP
Object-oriented programming patterns
Introduction
In this lesson, you'll learn about classes and oop in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with object-oriented programming patterns.
Python has its own approach to object-oriented programming patterns, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
class Animal:
def __init__(self, name, sound):
self.__name = name # private (name mangling)
self.sound = sound
def speak(self):
return f"{self.__name} says {self.sound}"
@property
def name(self):
return self.__name
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof")
def fetch(self, item):
return f"{self.name} fetched {item}!"
dog = Dog("Rex")
print(dog.speak())Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
class Animal {
#name; // private field
constructor(name, sound) {
this.#name = name;
this.sound = sound;
}
speak() {
return `${this.#name} says ${this.sound}`;
}
get name() { return this.#name; }
}
class Dog extends Animal {
constructor(name) {
super(name, "Woof");
}
fetch(item) {
return `${this.name} fetched ${item}!`;
}
}
const dog = new Dog("Rex");
console.log(dog.speak());You may be used to different syntax or behavior.
__init__ is Python's constructor
You may be used to different syntax or behavior.
self is explicit in every method (no 'this' magic)
You may be used to different syntax or behavior.
Double underscore __ for private (name mangling)
You may be used to different syntax or behavior.
@property decorator for getters
Step-by-Step Breakdown
1. The constructor
Python uses __init__ as the constructor. The first parameter is always self (the instance).
constructor(name) {
this.name = name;
}def __init__(self, name):
self.name = name2. Inheritance
Python inherits by putting the parent class in parentheses. super().__init__() calls the parent constructor.
class Dog extends Animal {
constructor(n) { super(n,"Woof"); }
}class Dog(Animal):
def __init__(self,n):
super().__init__(n,"Woof")3. Properties
Python's @property decorator creates a getter that can be accessed like an attribute.
get name() { return this.#name; }@property
def name(self):
return self.__nameCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- __init__ is Python's constructor
- self is explicit in every method (no 'this' magic)
- Double underscore __ for private (name mangling)
Key Takeaways
- __init__ = constructor, self = this
- class Dog(Animal) for inheritance
- @property for getters