JS Classes (Python Programming)
Learn JS Classes (Python Programming) step by step with clear examples and exercises.
Title: JavaScript Classes in Python Programming
Why This Matters
JavaScript classes are a powerful feature for structuring and organizing code, but they're often associated with web development. In this lesson, we'll learn how to use JavaScript-style classes in Python, which can make your code more readable and maintainable, especially when working on larger projects. This knowledge will be valuable for interviews, real-world programming tasks, and debugging common mistakes.
Prerequisites
To follow this lesson, you should have a basic understanding of:
- Python syntax, including variables, functions, and control structures
- Object-oriented programming concepts such as classes, objects, inheritance, and methods
Core Concept
In Python, we can use the class keyword to define a class, similar to JavaScript. A class is a blueprint for creating objects (also known as instances) that share properties and behaviors. Here's an example of a simple Python class:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
print("Engine started.")
def show_info(self):
print(f"This is a {self.brand} {self.model}.")
In this example, we have a Car class with three methods:
__init__: This special method is called when an instance of the class is created. It initializes the object's attributes (brand and model in this case).start_engine: A method that demonstrates some behavior or action of the car, such as starting the engine.show_info: A method that displays information about the car instance.
To create an instance (object) of the class, we can use the following syntax:
my_car = Car("Tesla", "Model S")
Now, we can call methods on my_car to interact with our car object:
my_car.start_engine() # Output: Engine started.
my_car.show_info() # Output: This is a Tesla Model S.
Class Variables and Methods
Class variables are shared among all instances of the class, while instance (or object) variables are unique to each instance. To define a class variable, simply assign it within the class body:
class Car:
num_wheels = 4
def __init__(self, brand, model):
self.brand = brand
self.model = model
Now, if we create multiple car instances, they will all have access to the num_wheels class variable:
my_car1 = Car("Tesla", "Model S")
my_car2 = Car("Ford", "Mustang")
print(my_car1.num_wheels) # Output: 4
print(my_car2.num_wheels) # Output: 4
Class methods are methods that operate on the class itself, rather than individual instances. To define a class method, use the @classmethod decorator:
class Car:
num_wheels = 4
@classmethod
def get_num_wheels(cls):
return cls.num_wheels
Now we can call this class method without creating an instance of the class:
print(Car.get_num_wheels()) # Output: 4
Inheritance and Polymorphism
Python supports inheritance, allowing one class to derive properties and methods from another class. This is useful for creating a hierarchy of related classes. To create a subclass that inherits from a superclass, use the class Car(SuperClass) syntax:
class Vehicle:
num_wheels = 4
def start_engine(self):
print("Engine started.")
class Car(Vehicle):
pass
my_car = Car()
print(my_car.num_wheels) # Output: 4
my_car.start_engine() # Output: Engine started.
In this example, the Car class inherits from the Vehicle superclass and gains access to its properties (num_wheels) and methods (start_engine).
Magic Methods
Python has several "magic" methods that allow us to customize object behavior. One example is the __str__ method, which allows us to define how an object's string representation should be formatted:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def __str__(self):
return f"{self.brand} {self.model}"
my_car = Car("Tesla", "Model S")
print(my_car) # Output: Tesla Model S
Static Methods
To define a static method, use the @staticmethod decorator:
class Car:
num_wheels = 4
@staticmethod
def get_num_wheels():
return Car.num_wheels
Static methods are not bound to any specific instance and can be called directly on the class:
print(Car.get_num_wheels()) # Output: 4
Worked Example
Let's create a simple bank account system using classes in Python. We will have two classes: Account and Bank. The Account class will represent individual accounts, while the Bank class will manage all accounts.
First, let's define our Account class:
class Account:
def __init__(self, account_number, balance):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds.")
return None
else:
self.balance -= amount
return self.balance
Now let's create our Bank class:
class Bank:
def __init__(self):
self.accounts = {}
def create_account(self, account_number, balance):
if account_number in self.accounts:
print("Account already exists.")
return None
else:
account = Account(account_number, balance)
self.accounts[account_number] = account
return account
def get_balance(self, account_number):
if account_number in self.accounts:
return self.accounts[account_number].balance
else:
print("Account not found.")
return None
def transfer(self, from_account_number, to_account_number, amount):
if from_account_number in self.accounts and to_account_number in self.accounts:
from_account = self.accounts[from_account_number]
to_account = self.accounts[to_account_number]
if from_account.withdraw(amount) is not None:
to_account.deposit(amount)
return True
else:
print("Transfer failed due to insufficient funds.")
return False
else:
print("One or both accounts not found.")
return False
Now we can use our Bank class to manage multiple accounts and perform transactions:
bank = Bank()
account1 = bank.create_account(12345, 1000)
account2 = bank.create_account(67890, 5000)
print(bank.get_balance(12345)) # Output: 1000
bank.transfer(12345, 67890, 2000) # Output: True
print(bank.get_balance(12345)) # Output: 800
Common Mistakes
- Forgetting to define the
__init__method in a class, which initializes instance variables. - Using instance variables instead of class variables when you want shared properties among all instances.
- Calling methods on an uninitialized instance, leading to undefined behavior or errors.
- Not understanding the difference between instance and class methods, resulting in incorrect method usage.
- Forgetting to define
__str__for customized string representation of objects. - Misusing inheritance by not defining required methods in subclasses or overriding methods improperly.
- Calling static or class methods on instances instead of the class itself.
Practice Questions
- Create a
Personclass with properties for name, age, and gender. Define methods to set and get these properties, as well as a method that prints a person's full name (first name + last name). - Modify the
Bankclass from the worked example to include an account list that keeps track of all accounts in ascending order by account number. - Create a
Rectangleclass with properties for width and height. Define methods to calculate the area, perimeter, and diagonal of the rectangle. - Implement a simple inheritance hierarchy: create a
Shapesuperclass with a method that calculates the area of the shape. Then create subclassesCircle,Square, andTrianglethat inherit fromShape. Each subclass should have its own implementation of the area calculation method.
FAQ
--
What is the difference between instance variables and class variables in Python?
Instance variables are unique to each instance (object) of a class, while class variables are shared among all instances.
Can I define methods without using the def keyword in Python?
No, you must use the def keyword to define methods in Python.
How do I call a static method in Python?
Static methods can be called directly on the class, without creating an instance of the class.
What is inheritance, and how does it work in Python?
Inheritance is a mechanism that allows one class to derive properties and methods from another class. In Python, you create a subclass by using the class SubClass(SuperClass) syntax.
Why do I need to define the __init__ method in my classes?
The __init__ method is used to initialize instance variables when an object is created. Without it, your objects may not have the expected initial state.