0% found this document useful (0 votes)
66 views

Programacià N Orientada A Objetos Python

1. The Account class defines a bank account with a name and balance. It includes methods to deposit, withdraw, and check the balance, raising errors for invalid transactions. 2. The Time class represents a time with hour, minute, and second attributes. It prints nicely with __str__ and displays all attributes with __repr__. Setting the attributes initializes a Time object. 3. The code shows initializing Account and Time objects, calling their methods, and handling errors as expected like disallowing negative deposits or withdrawals over the balance.

Uploaded by

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

Programacià N Orientada A Objetos Python

1. The Account class defines a bank account with a name and balance. It includes methods to deposit, withdraw, and check the balance, raising errors for invalid transactions. 2. The Time class represents a time with hour, minute, and second attributes. It prints nicely with __str__ and displays all attributes with __repr__. Setting the attributes initializes a Time object. 3. The code shows initializing Account and Time objects, calling their methods, and handling errors as expected like disallowing negative deposits or withdrawals over the balance.

Uploaded by

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

__repr__ __str__

__format__

object

doctest
Commission-
Employees Salaried-
Account CommissionEmployees
Account
Account

Complex
Time Complex
Time
Time

Card
DeckOfCards Card
Card Card

DeckOfCards

doctest

CommissionEmployee

SalariedCommissionEmployee
int float str list tuple dict
set Decimal array
Figure Axes Series DataFrame

conda pip

CommissionEmployee Time Card DeckOfCards


doctest

Account

Account

Account

Account ch10
Account
In [1]: from account import Account
Account

Account Decimal
Decimal
In [2]: from decimal import Decimal

Decimal
value = Decimal('12.34')

Account
Decimal
In [3]: account1 = Account('John Green', Decimal('50.00'))

Account name balance


In [4]: account1.name
Out[4]: 'John Green'

In [5]: account1.balance
Out[5]: Decimal('50.00')

Account deposit
In [6]: account1.deposit(Decimal('25.53'))

In [7]: account1.balance
Out[7]: Decimal('75.53')

Account
deposit ValueError
In [8]: account1.deposit(Decimal('-123.45'))
-------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-8-27dc468365a7> in <module>()
----> 1 account1.deposit(Decimal('-123.45'))

~/Documents/examples/ch10/account.py in deposit(self, amount)


21 # if amount is less than 0.00, raise an exception
22 if amount < Decimal('0.00'):
---> 23 raise ValueError('Deposit amount must be positive.')
24
25 self.balance += amount

ValueError: Deposit amount must be positive.


Account account.py

CommissionEmployee
# account.py
"""Account class definition."""
from decimal import Decimal

class Account:
"""Account class for maintaining a bank account balance."""

In [9]: Account?
Init signature: Account(name, balance)
Docstring: Account class for maintaining a bank account balance.
Init docstring: Initialize an Account object.
File: ~/Documents/examples/ch10/account.py
Type: type

Account
Account __init__
"Docstring:"
__init__ "Init docstring:"

[3]
account1 = Account('John Green', Decimal('50.00'))

__init__
None __init__
TypeError None
return Account __init__ Account
name balance balance
Account

def __init__(self, name, balance):


"""Initialize an Account object."""

# if balance is less than 0.00, raise an exception


if balance < Decimal('0.00'):
raise ValueError('Initial balance must be >= to 0.00.')

self.name = name
self.balance = balance

self self
Account __init__
name balance
if balance balance 0.00
__init__ ValueError __init__
Account name balance
Account

self. =

__init__
__

Account deposit amount balance


amount 0.00 ValueError
amount amount
balance
def deposit(self, amount):
"""Deposit money to the account."""

# if amount is less than 0.00, raise an exception


if amount < Decimal('0.00'):
raise ValueError('amount must be positive.')

self.balance += amount

Account name Account balance

Account name
Account balance Decimal
Circle Point Circle Point
Circle

__init__
__init__
__init__
None
withdraw Account amount
balance ValueError amount
balance amount 0.00
ValueError amount
amount balance Account
withdraw amount amount
balance amount
Account
def withdraw(self, amount):
"""Withdraw money from the account."""

# if amount is greater than balance, raise an exception


if amount > self.balance:
raise ValueError('amount must be <= to balance.')
elif amount < Decimal('0.00'):
raise ValueError('amount must be positive.')

self.balance -= amount

withdraw
In [1]: from account import Account

In [2]: from decimal import Decimal

In [3]: account1 = Account('John Green', Decimal('50.00'))

In [4]: account1.withdraw(Decimal('20.00'))

In [5]: account1.balance
Out[5]: Decimal('30.00')

In [6]: account1.withdraw(Decimal('100.00'))
-------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-61bb6aa89aa4> in <module>()
----> 1 account1.withdraw(Decimal('100.00'))
~/Documents/examples/ch10/snippets_py/account.py in withdraw(self,
amount)
30 # if amount is greater than balance, raise an exception
31 if amount > self.balance:
---> 32 raise ValueError('amount must be <= to balance.')
33 elif amount < Decimal('0.00'):
34 raise ValueError('amount must be positive.')

ValueError: amount must be <= to balance.

In [7]: account1.withdraw(Decimal('-10.00'))
-------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-ab50927d9727> in <module>()
----> 1 account1.withdraw(Decimal('-10.00'))

~/Documents/examples/ch10/snippets_py/account.py in withdraw(self,
amount)
32 raise ValueError('amount must be <= to balance.')
33 elif amount < Decimal('0.00'):
---> 34 raise ValueError('amount must be positive.')
35
36 self.balance -= amount

ValueError: amount must be positive.

Account balance
0.00
name balance
Account

In [1]: from account import Account

In [2]: from decimal import Decimal

In [3]: account1 = Account('John Green', Decimal('50.00'))

In [4]: account1.balance
Out[4]: Decimal('50.00')
account1 balance
balance
In [5]: account1.balance = Decimal('-1000.00')

In [6]: account1.balance
Out[6]: Decimal('-1000.00')

[6] account1 balance


_

_
Time

Time

Time
ch10 import Time timewithproperties.py
In [1]: from timewithproperties import Time

Time Time __init__ hour minute sec-


ond 0 hour
minute second 0
In [2]: wake_up = Time(hour=6, minute=30)

Time Time
[3] __repr__
__repr__
In [3]: wake_up
Out[3]: Time(hour=6, minute=30, second=0)
__str__
print __str__

In [4]: print(wake_up)
6:30:00 AM

hour minute second

wake_up hour
In [5]: wake_up.hour
Out[5]: 6

hour
hour _hour

Time set_time __init__


set_time hour minute second 0
In [6]: wake_up.set_time(hour=7, minute=45)

In [7]: wake_up
Out[7]: Time(hour=7, minute=45, second=0)

Time hour minute second


hour 6
In [8]: wake_up.hour = 6

In [9]: wake_up
Out[9]: Time(hour=6, minute=45, second=0)

[8]
hour 6
_hour

Time
hour ValueError

__str__
__repr__
In [10]: wake_up.hour = 100
-------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-10-1fce0716ef14> in <module>()
----> 1 wake_up.hour = 100

~/Documents/examples/ch10/timewithproperties.py in hour(self, hour)


20 """Set the hour."""
21 if not (0 <= hour < 24):
---> 22 raise ValueError(f'Hour ({hour}) must be 0-23')
23
24 self._hour = hour

ValueError: Hour (100) must be 0-23

print
__str__

__repr__

Time

Time __init__ hour minute second


0 Account __init__ self
Time
self.hour self.minute self.second hour minute second
Time self
hour minute second
_hour _minute _second

# timewithproperties.py
"""Class Time with read-write properties."""

class Time:
"""Class Time with read-write properties."""

def __init__(self, hour=0, minute=0, second=0):


"""Initialize each attribute."""
self.hour = hour # 0-23
self.minute = minute # 0-59
self.second = second # 0-59
hour
_hour _
_hour
[5] [8]
Time

@property
def hour(self):
"""Return the hour."""
return self._hour

@hour.setter
def hour(self, hour):
"""Set the hour."""
if not (0 <= hour < 24):
raise ValueError(f'Hour ({hour}) must be 0-23')

self._hour = hour

self
hour
_hour

wake_up.hour

@hour.setter
self
hour hour
self _hour
ValueError

wake_up.hour = 8

setter __init__
self.hour = hour

__init__ hour
_hour hour

minute second
setter 0 59
@property
def minute(self):
"""Return the minute."""
return self._minute

@minute.setter
def minute(self, minute):
"""Set the minute."""
if not (0 <= minute < 60):
raise ValueError(f'Minute ({minute}) must be 0-59')

self._minute = minute

@property
def second(self):
"""Return the second."""
return self._second

@second.setter
def second(self, second):
"""Set the second."""
if not (0 <= second < 60):
raise ValueError(f'Second ({second}) must be 0-59')

self._second = second

set_time
hour minute second
def set_time(self, hour=0, minute=0, second=0):
"""Set values of hour, minute, and second."""
self.hour = hour
self.minute = minute
self.second = second

repr

def __repr__(self):
"""Return Time string for repr()."""
return (f'Time(hour={self.hour}, minute={self.minute}, ' +
f'second={self.second})')

__repr__

'Time(hour=6, minute=30, second=0)'

https://docs.python.org/3/reference/datamodel.html
[2]

Time

Time
str
print str __str__
'7:59:59 AM' '12:30:45 PM'
def __str__(self):
"""Print Time in 12-hour clock format."""
return (('12' if self.hour in (0, 12) else str(self.hour % 12)) +
f':{self.minute:0>2}:{self.second:0>2}' +
(' AM' if self.hour < 12 else ' PM'))

print
__str__

Time time
hour minute second

Time

@property
def time(self):
"""Return hour, minute and second as a tuple."""
return (self.hour, self.minute, self.second)
@time.setter
def time(self, time_tuple):
"""Set time from a tuple containing hour, minute and second."""
self.set_time(time_tuple[0], time_tuple[1], time_tuple[2])

In [1]: from timewithproperties import Time

In [2]: t = Time()

In [3]: t
Out[3]: Time(hour=0, minute=0, second=0)

In [4]: t.time = (12, 30, 45)

In [5]: t
Out[5]: Time(hour=12, minute=30, second=45)

In [6]: t.time
Out[6]: (12, 30, 45)
self.set_time setter

self.set_time(*time_tuple)

*time_tuple time_tuple
setter
(12, 30, 45) self.set_time

self.set_time(12, 30, 45)

Time

Time

_hour _minute _second


In [1]: from timewithproperties import Time

In [2]: wake_up = Time(hour=7, minute=45, second=30)

In [3]: wake_up._hour
Out[3]: 7

In [4]: wake_up._hour = 100

In [5]: wake_up
Out[5]: Time(hour=100, minute=45, second=30)
[4] wake_up

hour minute sec-


ond

Time

https://docs.python.org/3/tutorial/classes.html#random-remarks
datetime
datetime
https://docs.python.org/3/library/datetime.html

Time
wake_up._hour = 100
_hour
__hour __hour

_
_Time__hour __hour
wake_up.__hour = 100

AttributeError __hour

wake_up.

wake_up

PrivateClass
public_data __private_data
# private.py
"""Class with public and private attributes."""

class PrivateClass:
"""Class with public and private attributes."""

def __init__(self):
"""Initialize the public and private attributes."""
self.public_data = "public" # public attribute
self.__private_data = "private" # private attribute

PrivateData
In [1]: from private import PrivateClass

In [2]: my_object = PrivateClass()

[3] public_data
In [3]: my_object.public_data
Out[3]: 'public'

__private_data [4]
AttributeError
In [4]: my_object.__private_data
-------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-d896bfdf2053> in <module>()
----> 1 my_object.__private_data

AttributeError: 'PrivateClass' object has no attribute '__private_data'


__private_data

__
__private_data
'_ ' PrivateData
__private_data

In [5]: my_object._PrivateClass__private_data
Out[5]: 'private'

In [6]: my_object._PrivateClass__private_data = 'modified'

In [7]: my_object._PrivateClass__private_data
Out[7]: 'modified'

Card 'Ace' '2' '3' 'Jack'


'Queen' 'King' 'Hearts' 'Diamonds' 'Clubs' 'Spades' DeckOf-
Cards Card

Card DeckOfCards

DeckOfCards deck.py
In [1]: from deck import DeckOfCards

In [2]: deck_of_cards = DeckOfCards()

https://docs.python.org/3/tutorial/classes.html#random-remarks
DeckOfCards __init__ Card
deck_of_cards
DeckOfCards __str__
Hearts
Diamonds Clubs Spades
In [3]: print(deck_of_cards)
Ace of Hearts 2 of Hearts 3 of Hearts 4 of Hearts
5 of Hearts 6 of Hearts 7 of Hearts 8 of Hearts
9 of Hearts 10 of Hearts Jack of Hearts Queen of Hearts
King of Hearts Ace of Diamonds 2 of Diamonds 3 of Diamonds
4 of Diamonds 5 of Diamonds 6 of Diamonds 7 of Diamonds
8 of Diamonds 9 of Diamonds 10 of Diamonds Jack of Diamonds
Queen of Diamonds King of Diamonds Ace of Clubs 2 of Clubs
3 of Clubs 4 of Clubs 5 of Clubs 6 of Clubs
7 of Clubs 8 of Clubs 9 of Clubs 10 of Clubs
Jack of Clubs Queen of Clubs King of Clubs Ace of Spades
2 of Spades 3 of Spades 4 of Spades 5 of Spades
6 of Spades 7 of Spades 8 of Spades 9 of Spades
10 of Spades Jack of Spades Queen of Spades King of Spades
deck_of_cards

In [4]: deck_of_cards.shuffle()

In [5]: print(deck_of_cards)
King of Hearts Queen of Clubs Queen of Diamonds 10 of Clubs
5 of Hearts 7 of Hearts 4 of Hearts 2 of Hearts
5 of Clubs 8 of Diamonds 3 of Hearts 10 of Hearts
8 of Spades 5 of Spades Queen of Spades Ace of Clubs
8 of Clubs 7 of Spades Jack of Diamonds 10 of Spades
4 of Diamonds 8 of Hearts 6 of Spades King of Spades
9 of Hearts 4 of Spades 6 of Clubs King of Clubs
3 of Spades 9 of Diamonds 3 of Clubs Ace of Spades
Ace of Hearts 3 of Diamonds 2 of Diamonds 6 of Hearts
King of Diamonds Jack of Spades Jack of Clubs 2 of Spades
5 of Diamonds 4 of Clubs Queen of Hearts 9 of Clubs
10 of Diamonds 2 of Clubs Ace of Diamonds 7 of Diamonds
9 of Spades Jack of Hearts 6 of Diamonds 7 of Clubs

Card deal_card
Card __repr__ Out[]
In [6]: deck_of_cards.deal_card()
Out[6]: Card(face='King', suit='Hearts')

Card __str__
str
In [7]: card = deck_of_cards.deal_card()

In [8]: str(card)
Out[8]: 'Queen of Clubs'
Card image_name
Card
In [9]: card.image_name
Out[9]: 'Queen_of_Clubs.png'

Card Card face suit


image_name
Card Card

Account name balance

Card

FACES
SUITS

# card.py
"""Card class that represents a playing card and its image file name."""

class Card:
FACES = ['Ace', '2', '3', '4', '5', '6',
'7', '8', '9', '10', 'Jack', 'Queen', 'King']
SUITS = ['Hearts', 'Diamonds', 'Clubs', 'Spades']

FACES SUITS

Card
Card
Card.FACES
Card.SUITS

Card __init__ _face _suit

def __init__(self, face, suit):


"""Initialize a Card with a face and suit."""
self._face = face
self._suit = suit

FACES SUITS
Card face suit image_name
face suit
_face _suit
Card image_name
Card
str(self) '.png'
'Ace of Spades' 'Ace_of_Spades.png'
Card

@property
def face(self):
"""Return the Card's self._face value."""
return self._face

@property
def suit(self):
"""Return the Card's self._suit value."""
return self._suit

@property
def image_name(self):
"""Return the Card's image file name."""
return str(self).replace(' ', '_') + '.png'

Card
Time __repr__
Card
def __repr__(self):
"""Return string representation for repr()."""
return f"Card(face='{self.face}', suit='{self.suit}')"

__str__ ' of ' 'Ace of Hearts'


def __str__(self):
"""Return string representation for str()."""
return f'{self.face} of {self.suit}'

Card __str__
DeckOfCards Card
Card Card

def __format__(self, format):


"""Return formatted string representation for str()."""
return f'{str(self):{format}}'
format
Card
str(self) __format__ __str__
DeckOfCards

DeckOfCards NUMBER_OF_CARDS
Card
_current_card Card 0 51
_deck Card

DeckOfCards __init__ _deck Card for


_deck Card
Card.FACES Card.SUITS count % 13
Card.FACES count // 13
Card.SUITS _deck
Card 'Ace' 'King' Hearts
Diamonds Clubs Spades
# deck.py
"""Deck class represents a deck of Cards."""
import random
from card import Card

class DeckOfCards:
NUMBER_OF_CARDS = 52 # constant number of Cards

def __init__(self):
"""Initialize the deck."""
self._current_card = 0
self._deck = []

for count in range(DeckOfCards.NUMBER_OF_CARDS):


self._deck.append(Card(Card.FACES[count % 13],
Card.SUITS[count // 13]))

shuffle _current_card 0 Card _deck


random shuffle
def shuffle(self):
"""Shuffle deck."""
self._current_card = 0
random.shuffle(self._deck)
deal_card Card _deck _current_card
0 51 Card Card
_deck _current_card
_current_card Card
None Card
def deal_card(self):
"""Return one Card."""
try:
card = self._deck[self._current_card]
self._current_card += 1
return card
except:
return None

DeckOfCards __str__
Card
Card __format__
'<19' format __format__ '<19'
Card
def __str__(self):
"""Return a string representation of the current _deck."""
s = ''

for index, card in enumerate(self._deck):


s += f'{self._deck[index]:<19}'
if (index + 1) % 4 == 0:
s += '\n'

return s

Card Card

https://commons.wikimedia.org/wiki/
Category:SVG_English_pattern_playing_cards

ch10 card_images
DeckOfCards
In [1]: from deck import DeckOfCards

In [2]: deck_of_cards = DeckOfCards()

https://creativecommons.org/publicdomain/zero/1.0/deed.en
%matplotlib
In [3]: %matplotlib
Using matplotlib backend: Qt5Agg

card_images
pathlib
[5] Path ch10
'.' Path

In [4]: from pathlib import Path

In [5]: path = Path('.').joinpath('card_images')

In [6]: import matplotlib.pyplot as plt

In [7]: import matplotlib.image as mpimg

Figure
nrows
ncols Figure
Axes figure axes_list
In [8]: figure, axes_list = plt.subplots(nrows=4, ncols=13)

Axes axes_list ravel


Axes

Card image_name
Path joinpath image_name
Path Path
Path str

matplotlib.image
Axes
In [9]: for axes in axes_list.ravel():
...: axes.get_xaxis().set_visible(False)
...: axes.get_yaxis().set_visible(False)
...: image_name = deck_of_cards.deal_card().image_name
...: img = mpimg.imread(str(path.joinpath(image_name).resolve()))
...: axes.imshow(img)
...:

Figure

In [10]: figure.tight_layout()

shuffle [9]
In [11]: deck_of_cards.shuffle()

In [12]: for axes in axes_list.ravel():


...: axes.get_xaxis().set_visible(False)
...: axes.get_yaxis().set_visible(False)
...: image_name = deck_of_cards.deal_card().image_name
...: img = mpimg.imread(str(path.joinpath(image_name).resolve()))
...: axes.imshow(img)
...:
Figure
Axes
subplots
Path appendpath Path
Path joinpath Path

Path Path('.')

Figure

In [13]: deck_of_cards.shuffle()

In [14]: figure, axes_list = plt.subplots(nrows=2, ncols=5)

In [15]: for axes in axes_list.ravel():


...: axes.get_xaxis().set_visible(False)
...: axes.get_yaxis().set_visible(False)
...: image_name = deck_of_cards.deal_card().image_name
...: img = mpimg.imread(str(path.joinpath(image_name).resolve()))
...: axes.imshow(img)
...:

In [16]: figure.tight_layout()
CarLoan
Loan HomeImprovementLoan MortgageLoan CarLoan
Loan Loan CarLoan
CarLoan Loan Loan
CarLoan Loan

Student GraduateStudent UndergraduateStudent


Shape Circle Triangle Rectangle Sphere Cube
Loan CarLoan HomeImprovementLoan MortgageLoan
Employee Faculty Staff
BankAccount CheckingAccount SavingsAccount

Vehicle
Car
Employee
CommunityMember Teacher Faculty CommunityMember
Employee Student Alum

Administrator Faculty
Employee CommunityMember object

Shape
Shape TwoDimensionalShape ThreeDim-
ensionalShape Shape TwoDimensionalShape ThreeDimensional-
Shape TwoDimensionalShape
ThreeDimensionalShape

Triangle TwoDimensionalShape Shape Sphere


ThreeDimensionalShape Shape
TwoDimensionalShape
ThreeDimensionalShape
Shape TwoDimensionalShape
Shape Circle Square Triangle

CommissionEmployee Salaried-
CommissionEmployee CommissionEmployee
SalariedCommissionEmployee

CommissionEmployee
__init__ _first_name
_last_name _ssn setter
gross_sales commission_rate
first_name last_name
ssn
gross_sales commission_rate
setter
earnings CommissionEm-
ployee
__repr__ Com-
missionEmployee

# commmissionemployee.py
"""CommissionEmployee base class."""
from decimal import Decimal
class CommissionEmployee:
"""An employee who gets paid commission based on gross sales."""

def __init__(self, first_name, last_name, ssn,


gross_sales, commission_rate):
"""Initialize CommissionEmployee's attributes."""
self._first_name = first_name
self._last_name = last_name
self._ssn = ssn
self.gross_sales = gross_sales # validate via property
self.commission_rate = commission_rate # validate via property

@property
def first_name(self):
return self._first_name

@property
def last_name(self):
return self._last_name

@property
def ssn(self):
return self._ssn

@property
def gross_sales(self):
return self._gross_sales

@gross_sales.setter
def gross_sales(self, sales):
"""Set gross sales or raise ValueError if invalid."""
if sales < Decimal('0.00'):
raise ValueError('Gross sales must be >= to 0')

self._gross_sales = sales

@property
def commission_rate(self):
return self._commission_rate

@commission_rate.setter
def commission_rate(self, rate):
"""Set commission rate or raise ValueError if invalid."""
if not (Decimal('0.0') < rate < Decimal('1.0')):
raise ValueError(
'Interest rate must be greater than 0 and less than 1')

self._commission_rate = rate

def earnings(self):
"""Calculate earnings."""
return self.gross_sales * self.commission_rate
def __repr__(self):
"""Return string representation for repr()."""
return ('CommissionEmployee: ' +
f'{self.first_name} {self.last_name}\n' +
f'social security number: {self.ssn}\n' +
f'gross sales: {self.gross_sales:.2f}\n' +
f'commission rate: {self.commission_rate:.2f}')

first_name last_name ssn

###-##-#### ######### #

object
object
CommissionEmployee
class CommissionEmployee(object):

CommissionEmployee

CommissionEmployee object object


object
__repr__ __str__

__repr__
CommissionEmployee object

CommissionEmployee Com-
missionEmployee
In [1]: from commissionemployee import CommissionEmployee

In [2]: from decimal import Decimal

In [3]: c = CommissionEmployee('Sue', 'Jones', '333-33-3333',


...: Decimal('10000.00'), Decimal('0.06'))
...:

In [4]: c
Out[4]:
CommissionEmployee: Sue Jones
social security number: 333-33-3333
gross sales: 10000.00
commission rate: 0.06

https://docs.python.org/3/reference/datamodel.html object
CommissionEmployee
In [5]: print(f'{c.earnings():,.2f}')
600.00

CommissionEmployee

In [6]: c.gross_sales = Decimal('20000.00')

In [7]: c.commission_rate = Decimal('0.1')

In [8]: print(f'{c.earnings():,.2f}')
2,000.00

[6]
c.gross_sales = Decimal('20000.00')

Decimal CommissionEmployee
gross_sales setter setter
Decimal('0.00') setter ValueError
setter
CommissionEmployee _gross_sales

SalariedCommissionEmployee
CommissionEmployee

SalariedCommissionEmployee
CommissionEmployee
SalariedCommissionEmployee

earnings

SalariedCommissionEmployee
CommissionEmployee SalariedCommissionEmployee
CommissionEmployee Commis-
sionEmployee SalariedCommissionEmployee
__init__
CommissionEmployee
base_salary setter _base_salary
base_salary setter

earnings
__repr__

# salariedcommissionemployee.py
"""SalariedCommissionEmployee derived from CommissionEmployee."""
from commissionemployee import CommissionEmployee
from decimal import Decimal

class SalariedCommissionEmployee(CommissionEmployee):
"""An employee who gets paid a salary plus
commission based on gross sales."""

def __init__(self, first_name, last_name, ssn,


gross_sales, commission_rate, base_salary):
"""Initialize SalariedCommissionEmployee's attributes."""
super().__init__(first_name, last_name, ssn,
gross_sales, commission_rate)
self.base_salary = base_salary # validate via property

@property
def base_salary(self):
return self._base_salary

@base_salary.setter
def base_salary(self, salary):
"""Set base salary or raise ValueError if invalid."""
if salary < Decimal('0.00'):
raise ValueError('Base salary must be >= to 0')

self._base_salary = salary

def earnings(self):
"""Calculate earnings."""
return super().earnings() + self.base_salary

def __repr__(self):
"""Return string representation for repr()."""
return ('Salaried' + super().__repr__() +
f'\nbase salary: {self.base_salary:.2f}')

import
class SalariedCommissionEmployee(CommissionEmployee):
SalariedCommissionEmployee CommissionEmployee
CommissionEmployee
SalariedCommissionEmployee

__init__ __init__

__init__ SalariedCommissionEmployee __init__


CommissionEmployee __init__
SalariedCommissionEmployee
CommissionEmployee super().__init__
__init__

SalariedCommissionEmployee earnings
CommissionEmployee earnings
SalariedCommissionEmployee
CommissionEmployee earnings
super().earnings() SalariedCommissionEmployee
earnings base_salary
SalariedCommissionEmployee earnings CommissionEm-
ployee earnings SalariedCommissionEmployee

SalariedCommissionEmployee __repr__ Commis-


sionEmployee __repr__ String
SalariedCommissionEmployee
'Salaried'
super().__repr__() CommissionEmployee __repr__

SalariedCommissionEmployee
CommissionEmployee SalariedCommissionEmployee

In [9]: from salariedcommissionemployee import SalariedCommissionEmployee

In [10]: s = SalariedCommissionEmployee('Bob', 'Lewis', '444-44-4444',


...: Decimal('5000.00'), Decimal('0.04'), Decimal('300.00'))
...:

In [11]: print(s.first_name, s.last_name, s.ssn, s.gross_sales,


...: s.commission_rate, s.base_salary)
Bob Lewis 444-44-4444 5000.00 0.04 300.00
SalariedCommissionEmployee
CommissionEmployee SalariedCommissionEmployee
SalariedCommissionEmployee
earnings SalariedCommissionEmployee

In [12]: print(f'{s.earnings():,.2f}')
500.00

gross_sales commission_rate base_salary


SalariedCommissionEmployee __repr__
In [13]: s.gross_sales = Decimal('10000.00')

In [14]: s.commission_rate = Decimal('0.05')

In [15]: s.base_salary = Decimal('1000.00')

In [16]: print(s)
SalariedCommissionEmployee: Bob Lewis
social security number: 444-44-4444
gross sales: 10000.00
commission rate: 0.05
base salary: 1000.00

SalariedCommissionEmployee
Salaried-
CommissionEmployee
In [17]: print(f'{s.earnings():,.2f}')
1,500.00

issubclass
In [18]: issubclass(SalariedCommissionEmployee, CommissionEmployee)
Out[18]: True

isinstance
SalariedCommissionEmployee CommissionEmployee
True
In [19]: isinstance(s, CommissionEmployee)
Out[19]: True

In [20]: isinstance(s, SalariedCommissionEmployee)


Out[20]: True

isinstance
SalariedCommissionEmployee earnings
return super().earnings() + self.base_salary

SalariedCommissionEmployee
super CommissionEmployee
base_salary

CommissionEmployee SalariedCommissionEmployee

In [21]: employees = [c, s]

In [22]: for employee in employees:


...: print(employee)
...: print(f'{employee.earnings():,.2f}\n')
...:
CommissionEmployee: Sue Jones
social security number: 333-33-3333
gross sales: 20000.00
commission rate: 0.10
2,000.00

SalariedCommissionEmployee: Bob Lewis


social security number: 444-44-4444
gross sales: 10000.00
commission rate: 0.05
base salary: 1000.00
1,500.00
for employee in employees:
print(employee)
print(f'{employee.earnings():,.2f}\n')

employees

print
earnings
object
print earnings

employees Com-
missionEmployee WellPaidDuck
In [1]: class WellPaidDuck:
...: def __repr__(self):
...: return 'I am a well-paid duck'
...: def earnings(self):
...: return Decimal('1_000_000.00')
...:

https://docs.python.org/3/glossary.html#term-duck-typing
WellPaidDuck
CommissionEmployee
SalariedCommissionEmployee WellPaidDuck
In [2]: from decimal import Decimal

In [3]: from commissionemployee import CommissionEmployee

In [4]: from salariedcommissionemployee import SalariedCommissionEmployee

In [5]: c = CommissionEmployee('Sue', 'Jones', '333-33-3333',


...: Decimal('10000.00'), Decimal('0.06'))
...:

In [6]: s = SalariedCommissionEmployee('Bob', 'Lewis', '444-44-4444',


...: Decimal('5000.00'), Decimal('0.04'), Decimal('300.00'))
...:

In [7]: d = WellPaidDuck()

In [8]: employees = [c, s, d]

In [9]: for employee in employees:


...: print(employee)
...: print(f'{employee.earnings():,.2f}\n')
...:
CommissionEmployee: Sue Jones
social security number: 333-33-3333
gross sales: 10000.00
commission rate: 0.06
600.00

SalariedCommissionEmployee: Bob Lewis


social security number: 444-44-4444
gross sales: 5000.00
commission rate: 0.04
base salary: 300.00
500.00

I am a well-paid duck
1,000,000.00
+

[]

object
__add__ + __mul__
*

https://docs.python.org/3/reference/datamodel.html#special-method-
names

Complex

+ * i

i int float Decimal


Complex +
Complex

Complex
Complex complexnumber.py
In [1]: from complexnumber import Complex
Complex [3] [5]
Complex __repr__
In [2]: x = Complex(real=2, imaginary=4)

In [3]: x
Out[3]: (2 + 4i)

In [4]: y = Complex(real=5, imaginary=-1)

In [5]: y
Out[5]: (5 - 1i)

__repr__ [3] [5]


__repr__ complex
+ Complex x y
2 5
4i -1i Complex
In [6]: x + y
Out[6]: (7 + 3i)

+
In [7]: x
Out[7]: (2 + 4i)

In [8]: y
Out[8]: (5 - 1i)

+= y x x +=

In [9]: x += y

In [10]: x
Out[10]: (7 + 3i)

In [11]: y
Out[11]: (5 - 1i)

Complex

__init__ real imaginary

j i 3+4j
real imag __repr__
'(3+4j)'
# complexnumber.py
"""Complex class with overloaded operators."""

class Complex:
"""Complex class that represents a complex number
with real and imaginary parts."""

def __init__(self, real, imaginary):


"""Initialize Complex class's attributes."""
self.real = real
self.imaginary = imaginary

+
Complex
def __add__(self, right):
"""Overrides the + operator."""
return Complex(self.real + right.real,
self.imaginary + right.imaginary)

self
right Complex __add__
Complex Complex
real imaginary

+=
Complex
def __iadd__(self, right):
"""Overrides the += operator."""
self.real += right.real
self.imaginary += right.imaginary
return self

__iadd__
self self

Complex
def __repr__(self):
"""Return string representation for repr()."""
return (f'({self.real} ' +
('+' if self.imaginary >= 0 else '-') +
f' {abs(self.imaginary)}i)')
a b a+b
c d c d
+

Complex - -=

complexnumber2.py
def __sub__(self, right):
"""Overrides the - operator."""
return Complex(self.real - right.real,
self.imaginary - right.imaginary)

def __isub__(self, right):


"""Overrides the -= operator."""
self.real -= right.real
self.imaginary -= right.imaginary
return self

In [1]: from complexnumber2 import Complex

In [2]: x = Complex(real=2, imaginary=4)

In [3]: y = Complex(real=5, imaginary=-1)

In [4]: x - y
Out[4]: (-3 + 5i)

In [5]: x -= y

In [6]: x
Out[6]: (-3 + 5i)

In [7]: y
Out[7]: (5 - 1i)

Base-
Exception

https://docs.python.org/3/library/exceptions.html
BaseException

SystemExit

KeyboardInterrupt

GeneratorExit
close
Exception
Exception ZeroDivisionError NameError
ValueError StatisticsError TypeError IndexError KeyError Runtime-
Error AttributeError StandardError

except

except
Exception Exception except
Exception except

Exception

Exception exceptions
namedtuple
In [1]: from collections import namedtuple

In [2]: Card = namedtuple('Card', ['face', 'suit'])

Card
Card
In [3]: card = Card(face='Ace', suit='Spades')

In [4]: card.face
Out[4]: 'Ace'

In [5]: card.suit
Out[5]: 'Spades'

In [6]: card
Out[6]: Card(face='Ace', suit='Spades')

In [7]: values = ['Queen', 'Hearts']

In [8]: card = Card._make(values)

In [9]: card
Out[9]: Card(face='Queen', suit='Hearts')

OrderedDict

In [10]: card._asdict()
Out[10]: OrderedDict([('face', 'Queen'), ('suit', 'Hearts')])

https://docs.python.org/3/library/
collections.html#collections.namedtuple
collections

namedtuple

namedtuple Time hour min-


ute second Time

In [1]: from collections import namedtuple

In [2]: Time = namedtuple('Time', ['hour', 'minute', 'second'])

In [3]: t = Time(13, 30, 45)

In [4]: print(t.hour, t.minute, t.second)


13 30 45

In [5]: t
Out[5]: Time(hour=13, minute=30, second=45)

__init__
__repr__

__init__ __repr__

==
__eq__ != object
__eq__
NotImplemented __eq__
< <= > >=

12. https://www.python.org/dev/peps/pep-0557/.
Card
carddataclass.py
Card DeckOfCards
Card

dataclasses

Card FACES SUITS


Card
FACES SUITS

# carddataclass.py
"""Card data class with class attributes, data attributes,
autogenerated methods and explicitly defined methods."""
from dataclasses import dataclass
from typing import ClassVar, List

@dataclass
@dataclass
class Card:

@dataclass

@dataclass(order=True)
< <= > >=

__init__

FACES SUITS
FACES: ClassVar[List[str]] = ['Ace', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'Jack', 'Queen', 'King']
SUITS: ClassVar[List[str]] = ['Hearts', 'Diamonds', 'Clubs', 'Spades']

https://docs.python.org/3/library/dataclasses.html#module-level-decorators-
classes-and-functions
: ClassVar[List[str]]

FACES
ClassVar List[str] SUITS

__init__ __repr__ __eq__

__init__
__init__ self. =
__init__

NameError
In [1]: from dataclasses import dataclass

In [2]: @dataclass
...: class Demo:
...: x # attempting to create a data attribute x
...:
-------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-79ffe37b1ba2> in <module>()
----> 1 @dataclass
2 class Demo:
3 x # attempting to create a data attribute x
4

<ipython-input-2-79ffe37b1ba2> in Demo()
1 @dataclass
2 class Demo:
----> 3 x # attempting to create a data attribute x
4

NameError: name 'x' is not defined

face suit ": str"

face: str
suit: str

https://www.python.org/dev/peps/pep-0526/
Card image_name
__str__ __format__ Card

@property
def image_name(self):
"""Return the Card's image file name."""
return str(self).replace(' ', '_') + '.png'

def __str__(self):
"""Return string representation for str()."""
return f'{self.face} of {self.suit}'

def __format__(self, format):


"""Return formatted string representation."""
return f'{str(self):{format}}'

str int float


typing ClassVar List

Card face
face

@dataclass

annotations

typing

< > >=


== != < > >=
@dataclass
order=True

Card Card
In [1]: from carddataclass import Card

In [2]: c1 = Card(Card.FACES[0], Card.SUITS[3])


Card __repr__ Card
In [3]: c1
Out[3]: Card(face='Ace', suit='Spades')

__str__ print Card


' of '
In [4]: print(c1)
Ace of Spades

In [5]: c1.face
Out[5]: 'Ace'

In [6]: c1.suit
Out[6]: 'Spades'

In [7]: c1.image_name
Out[7]: 'Ace_of_Spades.png'

Card ==
!= Card

In [8]: c2 = Card(Card.FACES[0], Card.SUITS[3])

In [9]: c2
Out[9]: Card(face='Ace', suit='Spades')

In [10]: c3 = Card(Card.FACES[0], Card.SUITS[0])

In [11]: c3
Out[11]: Card(face='Ace', suit='Hearts')

== !=
In [12]: c1 == c2
Out[12]: True

In [13]: c1 == c3
Out[13]: False

In [14]: c1 != c3
Out[14]: True

Card Card
deck2.py
DeckOfCards Card
import DeckOfCards print
print DeckOfCards __str__
Card Card __format__
Card
Hearts Diamonds Clubs Spades
In [15]: from deck2 import DeckOfCards # uses Card data class

In [16]: deck_of_cards = DeckOfCards()


In [17]: print(deck_of_cards)
Ace of Hearts 2 of Hearts 3 of Hearts 4 of Hearts
5 of Hearts 6 of Hearts 7 of Hearts 8 of Hearts
9 of Hearts 10 of Hearts Jack of Hearts Queen of Hearts
King of Hearts Ace of Diamonds 2 of Diamonds 3 of Diamonds
4 of Diamonds 5 of Diamonds 6 of Diamonds 7 of Diamonds
8 of Diamonds 9 of Diamonds 10 of Diamonds Jack of Diamonds
Queen of Diamonds King of Diamonds Ace of Clubs 2 of Clubs
3 of Clubs 4 of Clubs 5 of Clubs 6 of Clubs
7 of Clubs 8 of Clubs 9 of Clubs 10 of Clubs
Jack of Clubs Queen of Clubs King of Clubs Ace of Spades
2 of Spades 3 of Spades 4 of Spades 5 of Spades
6 of Spades 7 of Spades 8 of Spades 9 of Spades
10 of Spades Jack of Spades Queen of Spades King of Spades

Card
100 face Card face

In [1]: from carddataclass import Card

In [2]: c = Card('Ace', 'Spades')

In [3]: c
Out[3]: Card(face='Ace', suit='Spades')

In [4]: type(c.face)
Out[4]: str

In [5]: c.face = 100

In [6]: c
Out[6]: Card(face=100, suit='Spades')

In [7]: type(c.face)
Out[7]: int

False

16. https://www.python.org/dev/peps/pep-0526/.
__init__ __repr__ __eq__
< <= >
>=

https://www.python.org/dev/peps/pep-0557/

https://docs.python.org/3/library/dataclasses.html

doctest
doctest

>>>
testmod
testmod

accountdoctest.py Account
__init__

Account account1

account1 name

account1 balance

Account
ValueError

# accountdoctest.py
"""Account class definition."""
from decimal import Decimal

class Account:
"""Account class for demonstrating doctest."""

def __init__(self, name, balance):


"""Initialize an Account object.

>>> account1 = Account('John Green', Decimal('50.00'))


>>> account1.name
'John Green'
>>> account1.balance
Decimal('50.00')

The balance argument must be greater than or equal to 0.


>>> account2 = Account('John Green', Decimal('-50.00'))
Traceback (most recent call last):
...
ValueError: Initial balance must be >= to 0.00.
"""

>>> python
https://docs.python.org/3/library/doctest.html?highlight=doctest#module-doctest
# if balance is less than 0.00, raise an exception
if balance < Decimal('0.00'):
raise ValueError('Initial balance must be >= to 0.00.')

self.name = name
self.balance = balance

def deposit(self, amount):


"""Deposit money to the account."""

# if amount is less than 0.00, raise an exception


if amount < Decimal('0.00'):
raise ValueError('amount must be positive.')

self.balance += amount

if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)

__name__
accountdoctest.py '__main__'
__name__ if

doctest testmod

accountdoctest.py
testmod
testmod
verbose=True testmod

Trying:
account1 = Account('John Green', Decimal('50.00'))
Expecting nothing
ok
Trying:
account1.name
Expecting:
'John Green'
ok
Trying:
account1.balance
Expecting:
Decimal('50.00')
ok
Trying:
account2 = Account('John Green', Decimal('-50.00'))
doctest

Expecting:
Traceback (most recent call last):
...
ValueError: Initial balance must be >= to 0.00.
ok
3 items had no tests:
__main__
__main__.Account
__main__.Account.deposit
1 items passed all tests:
4 tests in __main__.Account.__init__
4 tests in 4 items.
4 passed and 0 failed.
Test passed.
testmod "Trying"
"Expecting" "ok"
testmod
accountdoctest.py
# accountdoctest.py

...
**********************************************************************
File "accountdoctest.py", line 18, in __main__.Account.__init__
Failed example:
account2 = Account('John Green', Decimal('-50.00'))
Expected:
Traceback (most recent call last):
...
ValueError: Initial balance must be >= to 0.00.
Got nothing
**********************************************************************
1 items had failures:
1 of 4 in __main__.Account.__init__
4 tests in 4 items.
3 passed and 1 failed.
***Test Failed*** 1 failures.

testmod
ValueError

__init__

In []
Out[] doctest
% doctest
%doctest_mode
>>>
%doctest_mode In [] Out[]
__name__
'__main__'
doctest testmod

doctest testmod

deposit
Account
ValueError

doctest
"""Deposit money to the account.

>>> account1 = Account('John Green', Decimal('50.00'))


>>> account1.deposit(Decimal('10.55'))
>>> account1.balance
Decimal('60.55')

>>> account1.deposit(Decimal('-100.00'))
Traceback (most recent call last):
...
ValueError: amount must be positive.
"""

Trying:
account1 = Account('John Green', Decimal('50.00'))
Expecting nothing
ok
Trying:
account1.name
Expecting:
'John Green'
ok
Trying:
account1.balance
Expecting:
Decimal('50.00')
ok
Trying:
account2 = Account('John Green', Decimal('-50.00'))
Expecting:
Traceback (most recent call last):
...
ValueError: Initial balance must be >= to 0.00.
ok
Trying:
account1 = Account('John Green', Decimal('50.00'))
Expecting nothing
ok
Trying:
account1.deposit(Decimal('10.55'))
Expecting nothing
ok
Trying:
account1.balance
Expecting:
Decimal('60.55')
ok
Trying:
account1.deposit(Decimal('-100.00'))
Expecting:
Traceback (most recent call last):
...
ValueError: amount must be positive.
ok
2 items had no tests:
__main__
__main__.Account
2 items passed all tests:
4 tests in __main__.Account.__init__
4 tests in __main__.Account.deposit
8 tests in 4 items.
8 passed and 0 failed.
Test passed.
'math' math 'random' random
doctest __name__ '__main__'
.py

input range int float str

In [1]: z = 'global z'

In [2]: def print_variables():


...: y = 'local y in print_variables'
...: print(y)
...: print(z)
...:

In [3]: print_variables()
local y in print_variables
global z

[3] print_variables

[3]

print_variables print_variables
print_variables

print_variables
print_variables y
y y
print_variables print y
y print
y
'local y in print_variables' print
print
print
print
print print
print
print_variables print
z
z z
'global z'
print print
print
print_variables

y
y y
In [4]: y
-------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-9063a9f0e032> in <module>()
----> 1 y

NameError: name 'y' is not defined

y
y y
y
NameError y
print_variables z
z
In [5]: z
Out[5]: 'global z'
object
NameError

__init__ self

NameError

ipython --matplotlib
c = 5 / 9 * (f - 32)

f c
c f

lambda

temps
In [1]: c = lambda f: 5 / 9 * (f - 32)

In [2]: temps = [(f, c(f)) for f in range(0, 101, 10)]

DataFrame
plot
style '.-'

'Celsius' plot
'Celsius'
In [3]: import pandas as pd

In [4]: temps_df = pd.DataFrame(temps, columns=['Fahrenheit', 'Celsius'])

In [5]: axes = temps_df.plot(x='Fahrenheit', y='Celsius', style='.-')

In [6]: y_label = axes.set_ylabel('Celsius')


linregress

DataFrame

DataFrame

https://www.ncdc.noaa.gov/cag/

https://en.wikipedia.org/wiki/Ordinary_least_squares
http://www.noaa.gov
ch10 ave_hi_nyc_jan_1895-2018.csv
"Date,Value,Anomaly"

Date 'YYYYMM’ '201801' MM 01

Value
Anomaly
Anomaly

ave_hi_nyc_jan_1895-2018.csv
In [7]: nyc = pd.read_csv('ave_hi_nyc_jan_1895-2018.csv')

DataFrame head tail


In [8]: nyc.head()
Out[8]:
Date Value Anomaly
0 189501 34.2 -3.2
1 189601 34.7 -2.7
2 189701 35.5 -1.9
3 189801 39.6 2.2
4 189901 36.4 -1.0

In [9]: nyc.tail()
Out[9]:
Date Value Anomaly
119 201401 35.5 -1.9
120 201501 36.1 -1.3
121 201601 40.8 3.4
122 201701 42.8 5.4
123 201801 38.7 1.3

Date Value
DataFrame DataFrame
'Value' 'Temperature'
In [10]: nyc.columns = ['Date', 'Temperature', 'Anomaly']

In [11]: nyc.head(3)
Out[11]:
Date Temperature Anomaly
0 189501 34.2 -3.2
1 189601 34.7 -2.7
2 189701 35.5 -1.9
Date

01 Date
In [12]: nyc.Date.dtype
Out[12]: dtype('int64')

DataFrame Series Series floordiv


Series
In [13]: nyc.Date = nyc.Date.floordiv(100)

In [14]: nyc.head(3)
Out[14]:
Date Temperature Anomaly
0 1895 34.2 -3.2
1 1896 34.7 -2.7
2 1897 35.5 -1.9

describe Temperature

In [15]: pd.set_option('precision', 2)

In [16]: nyc.Temperature.describe()
Out[16]:
count 124.00
mean 37.60
std 4.54
min 26.10
25% 34.58
50% 37.60
75% 40.60
max 47.60
Name: Temperature, dtype: float64

In [17]: from scipy import stats

In [18]: linear_regression = stats.linregress(x=nyc.Date,


...: y=nyc.Temperature)
...:

linregress
x y
linregress
slope intercept

Series
In [19]: linear_regression.slope
Out[19]: 0.00014771361132966167

In [20]: linear_regression.intercept
Out[20]: 8.694845520062952

linear_regression.slope 2019
linear_regression.intercept
In [21]: linear_regression.slope * 2019 + linear_regression.intercept
Out[21]: 38.51837136113298

In [22]: linear_regression.slope * 1890 + linear_regression.intercept


Out[22]: 36.612865774980335

regplot
Temperature
Date

regplot regplot x
y

Series
In [23]: import seaborn as sns

In [24]: sns.set_style('whitegrid')

In [25]: axes = sns.regplot(x=nyc.Date, y=nyc.Temperature)

In [26]: axes.set_ylim(10, 70)


Out[26]: (10, 70)

https://data.gov/

https://en.wikipedia.org/wiki/Simple_lin-
ear_regression#Confidence_intervals
ci=None regplot
https://www.ncdc.noaa.gov/cag/

https://www.esrl.noaa.gov/psd/data/timeseries/

https://www.quandl.com/search

https://datamarket.com/data/list/?q=provider:tsdl

http://archive.ics.uci.edu/ml/datasets.html

http://inforumweb.umd.edu/econdata/econdata.html

c = 5 / 9 * (f - 32) f
c

In [27]: year = 2019

In [28]: slope = linear_regression.slope

In [29]: intercept = linear_regression.intercept

In [30]: temperature = slope * year + intercept

In [31]: while temperature < 40.0:


...: year += 1
...: temperature = slope * year + intercept
...:

In [32]: year
Out[32]: 2120
__init__

__
Card
DeckOfCards Card
__repr__
__str__ __format__

object

__init__ __repr__ __eq__

doctest testmod

In [1]: try:
...: raise RuntimeError()
...: except Exception:
...: print('An Exception occurred')
...: except RuntimeError:
...: print('A RuntimeError occurred')
...:
An Exception occurred

Account
name balance

name balance
Time
universal_str Time
'22:30:00'
'06:30:00'
Time

_total_seconds hour minute


second _total_seconds
Time Time

CommissionEmployee SalariedCommissionEmployee

SalariedEmployee
CommissionEmployee SalariedCommissionEmployee SalariedEmployee
__repr__ earnings

Point x y
_x _y __init__ __repr__
move Point
Circle _radius _point Point
Circle __init__ __repr__
move Cir-
cle Point Circle
Circle Circle

datetime

x
y
datetime
datetime
datetime
y x

dataclasses

Card Card
Square
side __init__

perimeter 4 side
area side side
diagonal (2 side2)
perimeter area diagonal
side
Square side perimeter area diagonal
Invoice
Invoice

int Decimal
__init__

calculate_invoice
Invoice
fractions
Fraction

Fraction
Fraction
Fraction
Fraction
Fraction
Fraction a/b a b

Fraction float

complex complex
complex
complex
complex
complex
maximum
def maximum(value1, value2, value3):
"""Return the maximum of three values."""
max_value = value1
if value2 > max_value:
max_value = value2
if value3 > max_value:
max_value = value3
return max_value
maximum
int float

doctest
maximum

dataclasses
make_dataclass
make_dataclass
Account
['account', 'name', 'balance']

Account
== !=
int float str tuple

Complex
Complex

Account SavingsAccount
CheckingAccount SavingsAccount
SavingsAccount calculate_interest
Decimal SavingsAccount
deposit withdraw
CheckingAccount Decimal
CheckingAccount deposit
withdraw
CheckingAccount
Account CheckingAccount
withdraw

SavingsAc-
count calculate_interest
deposit

print
print
In [1]: z = 'global z'
In [2]: def print_variables():
...: y = 'local y in print_variables'
...: print(y)
...: print(z)
...: def nested_function():
...: x = 'x in nested function'
...: print(x)
...: print(y)
...: print(z)
...: nested_function()
...:

In [3]: print_variables()
local y in print_variables
global z
x in nested function
local y in print_variables
global z

ave_hi_la_jan_1895-2018.csv ch10

prospector
prospector

Card Card
face suit
prospector
https://github.com/PyCQA/prospector/blob/master/docs/
supported_tools.rst
Card DeckOfCards

DeckOfCards
'H'
'S'

Card
Card
functools total_ordering
@total_ordering __eq__ __lt__
< <= > >=

DeckOfCards
Hand
Hand

enum
Enum enum
Enum
Card enum

Shape Circle Square


Triangle draw draw
Circle Circle draw Square Square
draw Triangle Triangle
TwoDimensionalShape Shape
TwoDimensionalShape draw
TwoDimensionalShape

TwoDimensionalShape draw

TypeError
Shape Shape
TwoDimensionalShape ThreeDimensionalShape

Shape
Shape
Shape location color
draw move resize
Employee

Employee
Employee
SalariedEmployee HourlyEmployee Employee Employee

Employee

earnings
earnings
Employee
__init__

earnings abc

NotImplementedError

__repr__

Employee
earnings SalariedEmployee
__init__

Employee __init__
weekly_salary setter

__repr__ 'SalariedEmployee:'
SalariedEmployee
Employee
Employee earn-
ings HourlyEmployee

__init__

Employee __init__
hours wages setter

__repr__ 'HourlyEmployee:'
HourlyEmployee
Employee

Employee SalariedEmployee HourlyEmployee


Employee TypeError

SalariedEmployee HourlyEmployee

https://docs.python.org/3.7/library/exceptions.html#NotImplementedError

You might also like