

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Python 範例
<a name="examples-python"></a>

下列Python範例示範如何開始使用 Amazon Q Developer 產生內嵌程式碼建議。這些說明範例示範如何為您自己的專案觸發編碼助理。下列大多數範例適用於其他語言：
+ [產生類別和函數](#classes-python)
+ [文件程式碼](#code-python)
+ [產生演算法](#algorithms-python)
+ [產生單位測試](#tests-python)

## 產生類別和函數
<a name="classes-python"></a>

 若要產生完整或部分類別實作，請使用程式碼註解。註解說明 類別的意圖。開始簡單操作，並視需要新增更多詳細資訊。產生類別後，您可以繼續在其骨架內產生函數。

當您撰寫評論時，最好使用語言的評論結構。在 中Python，對於單行註解，請使用 `#`***。 ***對於多行註解，請使用 `''' '''`或 `""" """`。

輸入:

```
'''
DocumentReader class. has a name, children and optional parent. 
Includes I/O functions to read and
write document
'''
```

輸出：

```
class DocumentReader:
    def __init__(self, name, children, parent=None):
        self.name = name
        self.parent = parent
        self.children = children
        
    def read(self):
        """Reads current document and returns text"""
        pass
    
    def write(self, text):
        """Writes text to current document"""
        pass
```

現在有了初始類別，可以使用額外的註解產生額外的 函數。

輸入:

```
'''
function to read document from local directory path and print the first line of the document
'''
```

輸出：

```
def read_document(self, path):
        """Reads document from path and prints first line"""
        import os
        if os.path.isfile(path):
            with open(path, 'r') as f:
                print(f.readline())
        else:
            print(f"File not found at {path}")
```

## 文件程式碼
<a name="code-python"></a>

透過依賴內嵌文件來縮短程式碼文件中的時間。新增Python註解分隔符號 `''' '''`。

輸入:

```
class S3Utils:
    '''
    <place cursor here>
    '''
    def __init__(self):
        self.base_url = "https://s3"

    def generate_s3_url(self, bucket_name, region):
        return f"{self.base_url}.{region}.amazonaws.com/{bucket_name}"

# Example usage:
if __name__ == "__main__":
    s3_util = S3Utils()
    bucket_name = "my-example-bucket"
    region = "us-west-1"
    s3_url = s3_util.generate_s3_url(bucket_name, region)
    print(f"S3 URL for bucket '{bucket_name}' in region '{region}': {s3_url}")
```

輸出：

```
class S3Utils:
    '''
    Class to generate S3 URL from bucket name and region
    '''
    def __init__(self):
        self.base_url = "https://s3"

    def generate_s3_url(self, bucket_name, region):
        return f"{self.base_url}.{region}.amazonaws.com/{bucket_name}"

# Example usage:
if __name__ == "__main__":
    s3_util = S3Utils()
    bucket_name = "my-example-bucket"
    region = "us-west-1"
    s3_url = s3_util.generate_s3_url(bucket_name, region)
    print(f"S3 URL for bucket '{bucket_name}' in region '{region}': {s3_url}")
```

## 產生演算法
<a name="algorithms-python"></a>

Amazon Q Developer 可以產生熱門演算法，尤其是與 AWS SDKs相關的演算法。在指令碼中，新增一個提示來指定您想要的函數。

此範例示範如何產生使用者 ID 索引鍵的字典來命名值，然後使用泡泡排序演算法產生排序函數。

輸入:

```
class SortList:
    @staticmethod
    def get_user_id_name_map():
        user_id_name_map = {
            1: "Amit",
            2: "Rahul",
            3: "Vijay",
            4: "Raj",
            5: "Kumar"
        }
        return user_id_name_map
    

    '''
    Sort the list of user id's alphabetically using bubble sort
    '''
```

輸出：

```
    @staticmethod
    def sort_user_id_name_map():
        user_id_name_map = SortList.get_user_id_name_map()
        list_of_user_ids = list(user_id_name_map.keys())
        list_of_user_names = list(user_id_name_map.values())
        print("Before sort: ", list_of_user_ids)
        for i in range(len(list_of_user_ids)):
            for j in range(len(list_of_user_ids) - i - 1):
                if list_of_user_names[j] > list_of_user_names[j + 1]:
                    list_of_user_ids[j], list_of_user_ids[j + 1] = list_of_user_ids[j + 1], list_of_user_ids[j]
                    list_of_user_names[j], list_of_user_names[j + 1] = list_of_user_names[j + 1], list_of_user_names[j]
        print("After sort: ", list_of_user_ids)
```

此外，您可以建立標準程序的提示。在此範例中，使用者會建立提示，將字典存放到 Amazon DynamoDB 資料表。在指令碼的開頭，使用者會新增提示來新增 DynamoDB 程式庫，以協助為 Amazon Q Developer 提供額外的內容。

輸入:

```
'''
Add libraries for Amazon Dynamo DB
'''
```

輸出：

```
'''
Add libraries for Amazon Dynamo DB and JSON.

iMport necessary libraries for working with Amazon DynamoDB and JSON data.
'''

import boto3
import json
from botocore.exceptions import ClientError

def load_data_to_dynamodb(table_name, data_file):
    # Create a DynamoDB resource
    dynamodb = boto3.resource('dynamodb')

    # Get a reference to the table
    table = dynamodb.Table(table_name)

    # Load data from the JSON file
    with open(data_file, 'r') as file:
        data = json.load(file)

    # Iterate over the data and load it to the table
    for item in data:
        try:
            table.put_item(Item=item)
            print(f"Successfully loaded data: {item}")
        except ClientError as e:
            print(f"Error loading data: {e.response['Error']['Message']}")

# Example usage
load_data_to_dynamodb('myTable', 'data.json')
```

現在，使用者可以輕鬆要求 Amazon Q 協助將字典儲存在 DynamoDB 中。

輸入:

```
'''
   function to store the above sorted dict to dynamodb table named users    
'''
```

輸出：

```
@staticmethod
    def store_user_id_name_map_in_dynamodb():
        user_id_name_map = SortList.get_user_id_name_map()
        list_of_user_ids = list(user_id_name_map.keys())
        list_of_user_names = list(user_id_name_map.values())
        dynamodb = boto3.resource('dynamodb')
        table = dynamodb.Table('users')
        for i in range(len(list_of_user_ids)):
            try:
                response = table.put_item(
                    Item={
                        'user_id': list_of_user_ids[i],
                        'user_name': list_of_user_names[i]
                    }
                )
            except ClientError as e:
                print(e.response['Error']['Message'])
```

## 產生單位測試
<a name="tests-python"></a>

透過內嵌註解，Amazon Q Developer 可以產生單元測試，以執行聲明和其他測試。在此範例中，使用者要求 Amazon Q 產生適用的程式庫以進行單元測試，以設定測試指令碼的內容。然後，使用者要求 Amazon Q 為`sort_user_id_name_map`函數撰寫測試函數。

輸入:

```
'''
Import all the required unit test libraries for python and then generate a unit test for sort_user_id_name_map function.
'''
```

輸出：

```
import unittest
from unittest.mock import patch
from sort_user_id_name_map import sort_user_id_name_map

class TestSortUserIdNameMap(unittest.TestCase):
    @patch('sort_user_id_name_map.sort_user_id_name_map')
    def test_sort_user_id_name_map(self, mock_sort):
        mock_sort.return_value = {'id1': 'name1', 'id2': 'name2'}
        result = sort_user_id_name_map({'id2': 'name2', 'id1': 'name1'})
        self.assertEqual(result, {'id1': 'name1', 'id2': 'name2'})

if __name__ == '__main__':
    unittest.main()
```

此外，在使用者和 Amazon Q Developer 之間的聊天中，它會根據使用者的程式碼輸入提示來建議和產生單元測試。如需詳細資訊，請參閱[聊天範例](examples-chat.md)。