Programacià N Orientada A Objetos Python
Programacià N Orientada A Objetos Python
__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
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'))
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'))
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
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__
__
self.balance += amount
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."""
self.balance -= amount
withdraw
In [1]: from account import Account
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.')
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
Account balance
0.00
name balance
Account
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')
_
Time
Time
Time
ch10 import Time timewithproperties.py
In [1]: from timewithproperties import Time
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
wake_up hour
In [5]: wake_up.hour
Out[5]: 6
hour
hour _hour
In [7]: wake_up
Out[7]: Time(hour=7, minute=45, second=0)
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
print
__str__
__repr__
Time
# timewithproperties.py
"""Class Time with read-write properties."""
class Time:
"""Class Time with read-write properties."""
@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__
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 [2]: t = Time()
In [3]: t
Out[3]: Time(hour=0, minute=0, second=0)
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
Time
Time
In [3]: wake_up._hour
Out[3]: 7
In [5]: wake_up
Out[5]: Time(hour=100, minute=45, second=30)
[4] wake_up
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
[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
__
__private_data
'_ ' PrivateData
__private_data
In [5]: my_object._PrivateClass__private_data
Out[5]: 'private'
In [7]: my_object._PrivateClass__private_data
Out[7]: 'modified'
Card DeckOfCards
DeckOfCards deck.py
In [1]: from deck import 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
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
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}')"
Card __str__
DeckOfCards Card
Card Card
DeckOfCards NUMBER_OF_CARDS
Card
_current_card Card 0 51
_deck Card
class DeckOfCards:
NUMBER_OF_CARDS = 52 # constant number of Cards
def __init__(self):
"""Initialize the deck."""
self._current_card = 0
self._deck = []
DeckOfCards __str__
Card
Card __format__
'<19' format __format__ '<19'
Card
def __str__(self):
"""Return a string representation of the current _deck."""
s = ''
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
https://creativecommons.org/publicdomain/zero/1.0/deed.en
%matplotlib
In [3]: %matplotlib
Using matplotlib backend: Qt5Agg
card_images
pathlib
[5] Path ch10
'.' Path
Figure
nrows
ncols Figure
Axes figure axes_list
In [8]: figure, axes_list = plt.subplots(nrows=4, ncols=13)
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()
Path Path('.')
Figure
In [13]: deck_of_cards.shuffle()
In [16]: figure.tight_layout()
CarLoan
Loan HomeImprovementLoan MortgageLoan CarLoan
Loan Loan CarLoan
CarLoan Loan Loan
CarLoan Loan
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
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."""
@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}')
###-##-#### ######### #
object
object
CommissionEmployee
class CommissionEmployee(object):
CommissionEmployee
__repr__
CommissionEmployee object
CommissionEmployee Com-
missionEmployee
In [1]: from commissionemployee import CommissionEmployee
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 [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."""
@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__
SalariedCommissionEmployee earnings
CommissionEmployee earnings
SalariedCommissionEmployee
CommissionEmployee earnings
super().earnings() SalariedCommissionEmployee
earnings base_salary
SalariedCommissionEmployee earnings CommissionEm-
ployee earnings SalariedCommissionEmployee
SalariedCommissionEmployee
CommissionEmployee SalariedCommissionEmployee
In [12]: print(f'{s.earnings():,.2f}')
500.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
isinstance
SalariedCommissionEmployee earnings
return super().earnings() + self.base_salary
SalariedCommissionEmployee
super CommissionEmployee
base_salary
CommissionEmployee SalariedCommissionEmployee
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 [7]: d = WellPaidDuck()
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
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 [5]: y
Out[5]: (5 - 1i)
+
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
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."""
+
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)
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
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 [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
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
# 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__
__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
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}'
Card face
face
@dataclass
annotations
typing
Card Card
In [1]: from carddataclass import Card
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 [9]: c2
Out[9]: Card(face='Ace', suit='Spades')
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
Card
100 face Card face
In [3]: c
Out[3]: Card(face='Ace', suit='Spades')
In [4]: type(c.face)
Out[4]: str
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."""
>>> 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
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.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
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
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)
DataFrame
plot
style '.-'
'Celsius' plot
'Celsius'
In [3]: import pandas as pd
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"
Value
Anomaly
Anomaly
ave_hi_nyc_jan_1895-2018.csv
In [7]: nyc = pd.read_csv('ave_hi_nyc_jan_1895-2018.csv')
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')
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
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
regplot
Temperature
Date
regplot regplot x
y
Series
In [23]: import seaborn as sns
In [24]: sns.set_style('whitegrid')
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 [32]: year
Out[32]: 2120
__init__
__
Card
DeckOfCards Card
__repr__
__str__ __format__
object
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
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
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
SalariedEmployee HourlyEmployee
https://docs.python.org/3.7/library/exceptions.html#NotImplementedError