In this session, we'll explore more advanced topics in Python programming, including object-oriented programming (OOP) concepts, decorators, and an introduction to handling data with APIs.
Advanced Object-Oriented Programming
Inheritance
Inheritance allows one class to inherit attributes and methods from another class.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
Polymorphism
Polymorphism allows methods to be used in different ways for different objects.
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
print(animal.speak())
Decorators
Decorators are a way to modify the behavior of functions or methods. They are often used for logging, access control, or modifying input/output.
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Working with APIs
APIs (Application Programming Interfaces) allow you to interact with external services. Python's requests
library is commonly used to make HTTP requests.
Making a GET Request
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print(data)
else:
print("Failed to retrieve data")
Making a POST Request
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://api.example.com/data', json=payload)
if response.status_code == 201:
print("Data posted successfully")
else:
print("Failed to post data")
Handling JSON Data
JSON (JavaScript Object Notation) is a common format for data exchange. Python provides the json
module for working with JSON data.
Parsing JSON
import json
json_data = '{"name": "Alice", "age": 25}'
data = json.loads(json_data)
print(data['name']) # Output: Alice
Creating JSON
data = {'name': 'Alice', 'age': 25}
json_data = json.dumps(data)
print(json_data) # Output: {"name": "Alice", "age": 25}
These advanced topics will help you build more sophisticated and efficient Python applications, especially when dealing with larger codebases or integrating with external systems.