16-Composition Representation
16-Composition Representation
2
3
4
mate
class Animal:
5
mate
class Animal:
5
babies
class Rabbit(Animal):
def reproduce_like_rabbits(self):
if self.mate is None:
print("oh no! better go on ZoOkCupid")
return
self.babies = []
for _ in range(0, self.num_in_litter):
self.babies.append(Rabbit("bunny", 0))
6
babies
class Rabbit(Animal):
def reproduce_like_rabbits(self):
if self.mate is None:
print("oh no! better go on ZoOkCupid")
return
self.babies = []
for _ in range(0, self.num_in_litter):
self.babies.append(Rabbit("bunny", 0))
6
def partytime(animals):
"""Assuming ANIMALS is a list of Animals, cause each
to interact with all the others exactly once."""
for i in range(len(animals)):
for j in range(i + 1, len(animals)):
animals[i].interact_with(animals[j])
7
def partytime(animals):
"""Assuming ANIMALS is a list of Animals, cause each
to interact with all the others exactly once."""
for i in range(len(animals)):
for j in range(i + 1, len(animals)):
animals[i].interact_with(animals[j])
7
8
9
class Lamb:
species_name = "Lamb"
scientific_name = "Ovis aries"
def play(self):
self.happy = True
lamb = Lamb("Lil")
owner = "Mary"
had_a_lamb = True
fleece = {"color": "white", "fluffiness": 100}
kids_at_school = ["Billy", "Tilly", "Jilly"]
day = 1
10
class Lamb:
species_name = "Lamb"
scientific_name = "Ovis aries"
def play(self):
self.happy = True
lamb = Lamb("Lil")
owner = "Mary"
had_a_lamb = True
fleece = {"color": "white", "fluffiness": 100}
kids_at_school = ["Billy", "Tilly", "Jilly"]
day = 1
10
object
11
object
dir()
dir(object)
12
object
dir()
dir(object)
__repr__ __str__ __format__
__eq__ __ge__ __gt__ __le__ __lt__ __ne__
__bases__ __class__ __new__ __init__ __init_subclass__ __subclasshook__
__setattr__ __delattr__ __getattribute__
__dir__ __hash__ __module__ __reduce__ __reduce_ex__
12
13
__str__
one_third = 1/3
one_half = Fraction(1, 2)
float.__str__(one_third)
Fraction.__str__(one_half)
14
__str__
one_third = 1/3
one_half = Fraction(1, 2)
float.__str__(one_third) # '0.3333333333333333'
Fraction.__str__(one_half) # '1/2'
14
__str__
print() str()
from fractions import Fraction
one_third = 1/3
one_half = Fraction(1, 2)
print(one_third)
print(one_half)
str(one_third)
str(one_half)
15
__str__
print() str()
from fractions import Fraction
one_third = 1/3
one_half = Fraction(1, 2)
print(one_third) # '0.3333333333333333'
print(one_half) # '1/2'
str(one_third) # '0.3333333333333333'
str(one_half) # '1/2'
15
__str__
class Lamb:
species_name = "Lamb"
scientific_name = "Ovis aries"
def __str__(self):
return "Lamb named " + self.name
str(lil)
print(lil)
16
__repr__
one_half = Fraction(1, 2)
Fraction.__repr__(one_half) # 'Fraction(1, 2)'
eval()
another_half = eval(Fraction.__repr__(one_half))
17
__repr__
repr(object)
one_third = 1/3
one_half = Fraction(1, 2)
one_third
one_half
repr(one_third)
repr(one_half)
18
__repr__
class Lamb:
species_name = "Lamb"
scientific_name = "Ovis aries"
def __str__(self):
return "Lamb named " + self.name
def __repr__(self):
return f"Lamb({repr(self.name)})"
19
repr(obj)
ClassName.__repr__
ClassName.__repr__
__repr__
object.__repr__
str(obj)
ClassName.__str__
__str__
repr()
20
21
__init__
__repr__
__str__
__add__
__bool__
__float__
22
zero = 0
one = 1
two = 2
23
from math import gcd
class Rational:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.numer = numerator // g
self.denom = denominator // g
def __str__(self):
return f"{self.numer}/{self.denom}"
def __repr__(self):
return f"Rational({self.numer}, {self.denom})"
Rational(1, 2) + Rational(3, 4)
24
from math import gcd
class Rational:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.numer = numerator // g
self.denom = denominator // g
def __str__(self):
return f"{self.numer}/{self.denom}"
def __repr__(self):
return f"Rational({self.numer}, {self.denom})"
Rational(1, 2) + Rational(3, 4)
24
__add__
class Rational:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.numer = numerator // g
self.denom = denominator // g
# The rest...
25
__add__
class Rational:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.numer = numerator // g
self.denom = denominator // g
# The rest...
25
__add__
class Rational:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.numer = numerator // g
self.denom = denominator // g
# The rest...
Rational(1, 2) + Rational(3, 4)
25
26
str repr
repr(1/3) # '0.3333333333333333'
repr(Rational(1, 3)) # 'Rational(1, 3)'
str(1/3) # '0.3333333333333333'
str(Rational(1, 3)) # '1/3'
__str__ __repr__
27
def sum_two(a, b):
return a + b
a b
sum_two a b
28
def sum_two(a, b):
return a + b
a b
sum_two a b
28
def sum_em(items, initial_value):
"""Returns the sum of ITEMS,
starting with a value of INITIAL_VALUE."""
sum = initial_value
for item in items:
sum += item
return sum
items
initial_value
sum_em items
initial_value
29
def sum_em(items, initial_value):
"""Returns the sum of ITEMS,
starting with a value of INITIAL_VALUE."""
sum = initial_value
for item in items:
sum += item
return sum
items
initial_value
sum_em items
initial_value
29
def sum_em(items, initial_value):
"""Returns the sum of ITEMS,
starting with a value of INITIAL_VALUE."""
sum = initial_value
for item in items:
sum += item
return sum
items
initial_value
sum_em items
initial_value
29
def is_valid_month(month):
if isinstance(month, int):
return month >= 1 and month <= 12
elif isinstance(month, str):
return month in ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"]
return false
month
is_valid_month
month
30
def is_valid_month(month):
if isinstance(month, int):
return month >= 1 and month <= 12
elif isinstance(month, str):
return month in ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"]
return false
month
is_valid_month
month
30
def sum_numbers(nums):
"""Returns the sum of NUMS"""
sum = Rational(0, 0)
for num in nums:
if isinstance(num, int):
num = Rational(num, 1)
sum += num
return sum
nums
sum_numbers nums
31
def sum_numbers(nums):
"""Returns the sum of NUMS"""
sum = Rational(0, 0)
for num in nums:
if isinstance(num, int):
num = Rational(num, 1)
sum += num
return sum
nums
sum_numbers nums
31