

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

以下 Python 示例演示了如何开始使用 Amazon Q Developer 生成行内代码建议。这些说明性示例向您展示了如何为自己的项目触发编码助手。以下大多数示例适用于其他语言：
+ [生成类和函数](#classes-python)
+ [文件代码](#code-python)
+ [生成算法](#algorithms-python)
+ [生成单元测试](#tests-python)

## 生成类和函数
<a name="classes-python"></a>

 要生成全部或部分类实现，请使用代码注释。该评论描述了该班的意图。从简单开始，必要时添加更多细节。生成类后。您可以继续在其骨架中生成函数。

当你写评论时，最好使用该语言的注释结构。In 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 开发者提供更多背景信息。

输入:

```
'''
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)。