본문 바로가기

카테고리 없음

Python #7

In this session, we'll explore some specialized Python topics, including metaclasses, context managers in more depth, and an introduction to data analysis using pandas.

Metaclasses

Metaclasses are a deep and advanced topic in Python. They define the behavior of classes themselves, not just instances of classes. Essentially, a metaclass is a class of a class.

Basic Metaclass Example

class Meta(type):
    def __new__(cls, name, bases, dct):
        print(f"Creating class {name}")
        return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=Meta):
    pass

# Output: Creating class MyClass

Metaclasses are used in frameworks to modify or enhance classes automatically.

Advanced Context Managers

Beyond simple file handling, context managers can manage any resource that needs setup and teardown.

Creating Context Managers with Classes

class ManagedResource:
    def __enter__(self):
        print("Resource acquired")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print("Resource released")

with ManagedResource() as resource:
    print("Using resource")

Using contextlib for Simplicity

The contextlib module provides utilities for creating context managers more easily.

from contextlib import contextmanager

@contextmanager
def managed_resource():
    print("Resource acquired")
    try:
        yield
    finally:
        print("Resource released")

with managed_resource():
    print("Using resource")

Data Analysis with Pandas

Pandas is a powerful library for data manipulation and analysis. It provides data structures like Series and DataFrame.

Creating a DataFrame

import pandas as pd

data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

df = pd.DataFrame(data)
print(df)

Basic DataFrame Operations

  • Selecting Columns:

    print(df['Name'])
  • Filtering Rows:

    adults = df[df['Age'] > 30]
    print(adults)
  • Adding a New Column:

    df['Age in 10 Years'] = df['Age'] + 10
  • Descriptive Statistics:

    print(df.describe())

These topics will help you understand more complex Python features and how to apply them in real-world scenarios. Metaclasses allow for deep customization of class behavior; advanced context managers ensure resources are handled correctly; and pandas provides robust tools for data analysis.