1. Purpose of creating Fraction Class
Our purpose on this plot is to create a Python class called "Fraction". The operations for the Fraction class is as follows : Add, Subtract, Multiply, and Divide. And also, this class can show fractions using the standard "slash" form.
2. Defining Class
Fraction needs two pieces of data, the numerator and the denominator.
In OOP, all classes should provide constructor. The constructor defines the way in which data objects are created. The constructor method in class is always called __init__.
In constructor method, self is a special parameter that will always be used as reference ask to the object itself. To create an instance of the class, we must invoke the constructor. We can do above by using the name of the class and passing actual values for the necessary state.
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
myf = Fraction(3,5)
3. Standard Methods in Class
When we print the instance of class using print function, our return will be same as below.
myf = Fraction(3,5)
print(myf)
# <__main__.Fraction instance at 0x409b1acc>
This is because, the print function requires that the object convert itself into a string. The only choice instance has is to show the actual reference that is stored in the variable.
There are two ways we can solve this problem. One is defining a personal method to show, and the other is using a set of standard methods.
In Python, all classes have a set of standard methods that are provided but may not work properly. __str__ is the method to convert an object into a string.
However, the default implementation of standard methods is to return the instance address string. So, to do better implementation, we need to do implementation overrides which means redefining the method's behavior.
3.1 Overrides __str__ standard method
Now, the method will bulid a string representation by converting each piece of internal state data to a string and then placing a / chacter in between the strings using string concatenation.
class Fraction:
def __init__(self, top, bottom):
self.num = top
self.den = bottom
def __str__(self):
return str(self.num) + "/" + str(self.den)
3.2 Overrides __add__ standard method
We can apply other standard methods to implement arithmetic operations. Let's see when we apply __add__ methods to calculate summation with other fraction object.
def __add__(self, other_fraction):
newnum = self.num*other_fraction.den + self.den*other_fraction.num
newden = self.den*other_fraction.den
return Fraction(newnum, newden)
f1 = Fraction(1, 4)
f2 = Fraction(1, 2)
# 6 / 8
The method works as we desire, but one thing could be better. Note that 6 / 8 is the correct result but that is not the "lowest terms" representation. We can then divide the numerator and the denominator by the GCD.
def _gcd(self, m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
def __add__(self, other_fraction):
newnum = self.num*other_fraction.den + self.den*other_fraction.num
newden = self.den*other_fraction.den
gcd = self._gcd(newnum, newden)
return Fraction(newnum//gcd, newden//gcd)
f1 = Fraction(1, 4)
f2 = Fraction(1, 2)
# 3 / 4
3.3 Overrides __eq__ standard method
The __eq__ method compares two objects and returns True if their values are the same, False otherwise. In the Fraction class, we can implement the __eq__ method by agian putting the two fractions in common term and then comparing the numerators.
def __eq__(self, other):
firstnum = self.num * other.den
secondnum = other.num * self.den
return firstnum == secondnum
Source from : https://runestone.academy/ns/books/published/pythonds/Introduction/ObjectOrientedProgramminginPythonDefiningClasses.html
'Language > Python' 카테고리의 다른 글
[sys] The way to import module not found (0) | 2022.10.03 |
---|---|
[OOP] Implement Logic Gates using Class Inheritance (0) | 2022.10.03 |
[Syntax] Meaning of dot Notation (0) | 2022.09.26 |
[collections] Make frequency table automatically (1) | 2022.09.23 |
[chardet] Encoding and Representing Text (0) | 2022.09.22 |