Advanced Python

Advanced Python Concepts

1. Object-Oriented Programming (OOP)

Python supports object-oriented programming (OOP), which allows for code reusability and modularity.

Classes and Objects


class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display(self):
        print(f"Car: {self.brand} {self.model}")

# Creating an object
my_car = Car("Toyota", "Corolla")
my_car.display()
        

Inheritance

Inheritance allows one class to derive properties from another.


class Vehicle:
    def __init__(self, brand):
        self.brand = brand

    def honk(self):
        print("Honk! Honk!")

class Car(Vehicle):
    def __init__(self, brand, model):
        super().__init__(brand)
        self.model = model

    def display(self):
        print(f"Car: {self.brand} {self.model}")

my_car = Car("Tesla", "Model S")
my_car.display()
my_car.honk()
        

2. Decorators

Decorators allow you to modify the behavior of functions or classes dynamically.


def decorator_function(original_function):
    def wrapper_function():
        print("Wrapper executed before", original_function.__name__)
        return original_function()
    return wrapper_function

@decorator_function
def say_hello():
    print("Hello, World!")

say_hello()
        

3. Generators

Generators are functions that allow you to iterate over data lazily using the yield keyword.


def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

for num in count_up_to(5):
    print(num)
        

4. Multithreading

Python’s threading module allows for concurrent execution of code.


import threading

def print_numbers():
    for i in range(5):
        print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
print("Thread finished execution")
        

5. File Handling

Python allows reading and writing files easily.

Writing to a File


with open("example.txt", "w") as file:
    file.write("Hello, this is a test file!")
        

Reading from a File


with open("example.txt", "r") as file:
    content = file.read()
    print(content)
        

6. Lambda Functions

Lambda functions are small, anonymous functions useful for short operations.


square = lambda x: x ** 2
print(square(5))  # Output: 25
        

7. Working with JSON

Python's json module is used to work with JSON data.

Converting Python Dictionary to JSON


import json

data = {"name": "Alice", "age": 25}
json_data = json.dumps(data)
print(json_data)
        

Reading JSON Data


import json

json_string = '{"name": "Alice", "age": 25}'
data = json.loads(json_string)
print(data["name"])  # Output: Alice
        

8. Regular Expressions

Python's re module is used for pattern matching.


import re

pattern = r"\d{3}-\d{2}-\d{4}"
text = "My number is 123-45-6789"
match = re.search(pattern, text)
if match:
    print("Match found:", match.group())
        

9. Exception Handling

Python allows handling errors gracefully using try-except.


try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This will always execute.")
        

10. Working with Databases (SQLite Example)

Python has built-in support for SQLite databases.

Creating a Database and Table


import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES ('Alice')")

conn.commit()
conn.close()
        

Reading Data from the Database


import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

cursor.execute("SELECT * FROM users")
print(cursor.fetchall())

conn.close()
        

Conclusion

Now that you've explored advanced Python concepts, you're ready to take on real-world projects and optimize your code for performance!

Want to review the basics? Check out our Basic Python Tutorial.

Python Interpreter 1

Test Your Knowledge Here



    
        

Python Interpreter 2

Test Your Coding Skills Here