0% found this document useful (0 votes)
42 views46 pages

16-Composition Representation

The document describes a class called Rational that represents fractions. It defines methods like __init__, __add__, __str__, and __repr__ to initialize rational number objects and perform operations on them. It also shows how to add two Rational objects by implementing the __add__ method.

Uploaded by

Alex s
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)
42 views46 pages

16-Composition Representation

The document describes a class called Rational that represents fractions. It defines methods like __init__, __add__, __str__, and __repr__ to initialize rational number objects and perform operations on them. It also shows how to add two Rational objects by implementing the __add__ method.

Uploaded by

Alex s
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/ 46

1

2
3
4
mate
class Animal:

def mate_with(self, other):


if other is not self and other.species_name == self.species_name:
self.mate = other
other.mate = self

5
mate
class Animal:

def mate_with(self, other):


if other is not self and other.species_name == self.species_name:
self.mate = other
other.mate = self

mr_wabbit = Rabbit("Mister Wabbit", 3)


jane_doe = Rabbit("Jane Doe", 2)
mr_wabbit.mate_with(jane_doe)

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

mr_wabbit = Rabbit("Mister Wabbit", 3)


jane_doe = Rabbit("Jane Doe", 2)
mr_wabbit.mate_with(jane_doe)
jane_doe.reproduce_like_rabbits()

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])

jane_doe = Rabbit("Jane Doe", 2)


scar = Lion("Scar", 12)
elly = Elephant("Elly", 5)
pandy = Panda("PandeyBear", 4)
partytime([jane_doe, scar, elly, pandy])

7
8
9
class Lamb:
species_name = "Lamb"
scientific_name = "Ovis aries"

def __init__(self, name):


self.name = name

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 __init__(self, name):


self.name = name

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

lamb owner had_a_lamb fleece kids_at_school day


object.__class__.__bases__

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__

from fractions import Fraction

one_third = 1/3
one_half = Fraction(1, 2)

float.__str__(one_third)
Fraction.__str__(one_half)

14
__str__

from fractions import Fraction

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)

f"{one_half} > {one_third}"

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'

f"{one_half} > {one_third}" # '1/2 > 0.3333333333333333'

15
__str__

class Lamb:
species_name = "Lamb"
scientific_name = "Ovis aries"

def __init__(self, name):


self.name = name

def __str__(self):
return "Lamb named " + self.name

lil = Lamb("Lil lamb")

str(lil)

print(lil)

16
__repr__

from fractions import Fraction

one_half = Fraction(1, 2)
Fraction.__repr__(one_half) # 'Fraction(1, 2)'

eval()

another_half = eval(Fraction.__repr__(one_half))

17
__repr__
repr(object)

from fractions import Fraction

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 __init__(self, name):


self.name = name

def __str__(self):
return "Lamb named " + self.name

def __repr__(self):
return f"Lamb({repr(self.name)})"

lil = Lamb("Lil lamb")


repr(lil)
lil

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

one + two # 3 one.__add__(two) # 3

bool(zero) # False zero.__bool__() # False

bool(one) # True one.__bool__() # True

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

def __add__(self, other):


# The rest...

25
__add__
class Rational:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.numer = numerator // g
self.denom = denominator // g

def __add__(self, other):


new_numer = self.numer * other.denom + other.numer * self.denom
new_denom = self.denom * other.denom
return Rational(new_numer, new_denom)

# The rest...

25
__add__
class Rational:
def __init__(self, numerator, denominator):
g = gcd(numerator, denominator)
self.numer = numerator // g
self.denom = denominator // g

def __add__(self, other):


new_numer = self.numer * other.denom + other.numer * self.denom
new_denom = self.denom * other.denom
return Rational(new_numer, new_denom)

# 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

You might also like