0% found this document useful (0 votes)
2 views4 pages

as5

The document contains exercises focused on using the typing library for type hinting in Python, including dictionaries, lists, and custom classes. It also covers accessing and modifying attributes in a class using the @property decorator, specifically for a BankAccount class. The exercises guide users through creating type hints for various data structures and implementing property methods for class attributes.

Uploaded by

kamilamuatova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

as5

The document contains exercises focused on using the typing library for type hinting in Python, including dictionaries, lists, and custom classes. It also covers accessing and modifying attributes in a class using the @property decorator, specifically for a BankAccount class. The exercises guide users through creating type hints for various data structures and implementing property methods for class attributes.

Uploaded by

kamilamuatova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

Exercise-1

Using the Typing library


The typing library helps when adding type hints to objects such as dictionaries and
lists, as well as the elements in those objects. In this exercise, you'll practice
exactly that. Go get 'em!

Instructions
From the typing library, import Dict and List.
Using a class imported from typing, add type hints to the roster dictionary to
include details about the types of keys and values.
Update the creation of the agents list to add type hints for both the object
itself, as well as the type of the elements it stores.

# Import Dict and List from typing


from ____ import ____, ____

# Type hint the roster of codenames and number of missions


roster: ____[____, ____] = {
"Chuck": 37,
"Devin": 2,
"Steven": 4
}

# Unpack the values and add type hints for the new list
agents: ____[____] = [
f"Agent {agent}, {missions} missions" \
for agent, missions in roster.items()
]

--------------------------------------------------
Exercise-2
Type hinting with custom classes
In this exercise, you'll use built-in type keywords, the typing library, and your
own custom class to practice type hinting. List has been imported from the typing
library. Time to get started!

Instructions 1/3
Create an Agent class that takes the parameters codename (a string), and missions
(an integer); add type hints to both the constructor definition, and the method
itself.
# Define an agent class with a constructor, add type hints
class Agent:
def __init__(self, ____: ____, ____: ____):
self.____: ____ = codename
self.____: int = ____

------------------------------------------------------------------
Instructions 2/3
Define an add_mission() method that takes a single parameter, location (a string),
and returns no value; make sure to add type hints to the definition of the method.
class Agent:
def __init__(self, codename: str, missions: int):
self.codename: str = codename
self.missions: int = missions

# Create the add_mission() method, add type hinting


def add_mission(self, ____: ____) ____ ____:
self.missions += 1
print(f"{self.codename} completed a mission in " + \
f"{location}. This was mission #{self.missions}")

-----------------------------------------------------
Instructions 3/3
Add type hints to the definition of an Agent object, called chuck.
Create and type hint a list of locations (all strings), and use the chuck object to
add a mission for each of these locations.
class Agent:
def __init__(self, codename: str, missions: int):
self.codename: str = codename
self.missions: int = missions

def add_mission(self, location: str) -> None:


self.missions += 1
print(f"{self.codename} completed a mission in " + \
f"{location}. This was mission #{self.missions}")

# Create an Agent object, add type hints


____: ____ = ____("Charles Carmichael", 37)

# Create a list of locations, add a mission for each


____: ____[____] = ["Burbank", "Paris", "Prague"]
for location in locations:
chuck.add_mission(location)

--------------------------------------------------------------
CLASS WORK
Exercise-1
Accessing the balance attribute
In this exercise, you'll practice accessing the balance attribute of a BankAccount
class
that's implemented a descriptor using the @property decorator.
The BankAccount class has been created for you, as shown below:

class BankAccount:
def __init__(self, balance):
self.balance = balance

@property
def balance(self):
return f"${round(self._balance, 2)}"

@balance.setter
def balance(self, new_balance):
if new_balance > 0:
self._balance = new_balance

@balance.deleter
def balance(self):
print("Deleting the 'balance' attribute")
del self._balance
Instructions
Output the balance attribute of the newly-created checking_account object using
print().
Set the value of balance to 150 and again output the updated attribute.
Delete the balance attribute from the checking_account object.

-----CODE----
checking_account = BankAccount(100)

# Output the balance of the checking_account object


print(____.____)

# Set the balance to 150, output the new balance


____.____ = ____
print(____.____)

# Delete the balance attribute, attempt to print the balance


____ checking_account.____

-----------------------------------------------------------

Exercise-2
Using the @property decorator
Now that you've practiced working with a class that implements descriptors, you'll
get to build your own using the @property decorator. Good luck!

Instructions 1/3
Use the @property decorator to begin the process of creating a descriptor for the
email attribute; this method will return the email address inside of an f-string.
----CODE----
class BankAccount:
def __init__(self, email):
self.email = email

# Define and decorate a method to begin the process of


# creating a descriptor for the email attribute
@____
def ____(self):
return f"Email for this account is: {____.____}"

------------------------------------------------
Instructions 2/3
Create and decorate a method in the BankAccount class to set the value of the email
attribute, if the new email address contains the @ symbol
---CODE---
class BankAccount:
def __init__(self, email):
self.email = email

@property
def email(self):
return f"Email for this account is: {self._email}"

# Build a method to update the value of email using the


# new email address, if it contains the "@" symbol
@email.____
def ____(self, new_email_address):
if "@" in ____:
self._email = ____
else:
print("Please make sure to enter a valid email.")

-----------------------------------------------------------------------
Instructions 3/3
Define and decorate a method that will be used when the email attribute is deleted
from a BankAccount object.
----CODE---
class BankAccount:
def __init__(self, email):
self.email = email

@property
def email(self):
return f"Email for this account is: {self._email}"

@email.setter
def email(self, new_email_address):
if "@" in new_email_address:
self._email = new_email_address
else:
print("Please make sure to enter a valid email.")

# Define a method to be used when deleting the email attribute


@____.____
def ____(self):
____ self._email
print("Email deleted, make sure to add a new email!")

-----------------------------------------------------------------

You might also like