forked from a-newman/python-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13_intro_classes.py
More file actions
42 lines (34 loc) · 1.6 KB
/
13_intro_classes.py
File metadata and controls
42 lines (34 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# ** Classes **
# In addition to objects like lists and dictionaries, Python also lets you
# define your own data types. These are known as classes.
# Classes can be pretty complicated, but the basics are fairly simple. Skim the
# following links to learn more about how classes work:
# Introduction to classes:
# https://www.w3schools.com/python/python_classes.asp
# Python 3 documentation about classes:
# https://docs.python.org/3/tutorial/classes.html
# ** Exercises **
# 1. Below, write a class called Fraction that represents a real fraction.
# It should have two fields, `numerator` and `denominator`, which are
# passed in in the __init__ function. It should also support a method
# `multiply(other_fraction)`, which takes in a `Fraction` and returns
# another `Fraction` representing the product of itself and `other_fraction`.
class Fraction:
def __init__(self, numerator, denominator):
# save numerator and denominator as fields of this class with the same
# name
# Your code here
pass
def multiply(self, other):
# return a new Fraction whose `numerator` is the product of this
# class' numerator and other's numerator
# and whose `denominator` is the product of htis class' denominator and
# other's denominator
# Your code here
pass
# Test your code
f1 = Fraction(1, 2) # represents the fraction 1/2
f2 = Fraction(3, 4) # represents the fraction 3/4
product = f1.multiply(f2) # represents (1/2)*(3/4) = 3/8
print("Product (should be 3/8): "
+ str(product.numerator) + "/" + str(product.denominator))