

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

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

I seguenti Python alcuni esempi dimostrano come iniziare a generare suggerimenti di codice in linea con Amazon Q Developer. Questi esempi illustrativi mostrano come attivare l'assistente di programmazione per i tuoi progetti. La maggior parte dei seguenti esempi è applicabile ad altre lingue:
+ [Genera classi e funzioni](#classes-python)
+ [Codice del documento](#code-python)
+ [Genera algoritmi](#algorithms-python)
+ [Genera test unitari](#tests-python)

## Genera classi e funzioni
<a name="classes-python"></a>

 Per generare un'implementazione completa o parziale della classe, utilizzate i commenti al codice. Il commento descrive l'intenzione della classe. Inizia in modo semplice e aggiungi altri dettagli se necessario. Dopo aver generato una classe, potete continuare a generare funzioni all'interno della relativa struttura.

Quando scrivi commenti, è preferibile utilizzare la struttura dei commenti del linguaggio. In Python***, per commenti a riga singola, usa`#`.***Per commenti su più righe, usa `''' '''` o`""" """`.

Input:

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

Output:

```
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
```

Ora che esiste una classe iniziale, è possibile generare una funzione aggiuntiva con commenti aggiuntivi.

Input:

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

Output:

```
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}")
```

## Codice del documento
<a name="code-python"></a>

Riduci i tempi di redazione della documentazione in codice affidandoti alla documentazione in linea. Add (Aggiungi) Python interruzioni di commento. `''' '''`

Input:

```
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}")
```

Output:

```
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}")
```

## Genera algoritmi
<a name="algorithms-python"></a>

Amazon Q Developer può generare algoritmi popolari, in particolare quelli relativi a AWS SDKs. Nello script, aggiungi un prompt che specifica la funzione che desideri. 

Questo esempio mostra come generare un dizionario di chiavi ID utente per denominare i valori e quindi generare una funzione di ordinamento utilizzando l'algoritmo di ordinamento a bolle.

Input:

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

Output:

```
    @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)
```

Inoltre, è possibile creare istruzioni per le procedure standard. In questo esempio, l'utente crea un prompt per memorizzare il dizionario in una tabella Amazon DynamoDB. All'inizio dello script, l'utente aggiunge un prompt per aggiungere librerie DynamoDB per fornire ad Amazon Q Developer un contesto aggiuntivo.

Input:

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

Output:

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

Ora, l'utente può facilmente chiedere ad Amazon Q di aiutarlo a memorizzare il dizionario in DynamoDB.

Input:

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

Output:

```
@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'])
```

## Genera test unitari
<a name="tests-python"></a>

Con i commenti in linea, Amazon Q Developer può generare test unitari per eseguire asserzioni e altri test. In questo esempio, l'utente chiede ad Amazon Q di generare librerie applicabili per il test unitario per impostare il contesto dello script di test. Quindi, l'utente chiede ad Amazon Q di scrivere una funzione di test per la `sort_user_id_name_map` funzione.

Input:

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

Output:

```
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()
```

Inoltre, in una chat tra l'utente e Amazon Q Developer, suggerisce e genera test unitari in base alle richieste di immissione del codice dell'utente. Per ulteriori informazioni, consulta Esempi di [chat](examples-chat.md).