I'm writting a Fraction
class and I am trying to use gcd(a,b)
in the initialization of a Fraction
object. However, when I was trying to do this it would not work WITHOUT the Fraction
part of Fraction.gcd(a,b)
. I used @staticmethod
here, but it does absolutely nothing, i.e. my code works the same without it.
Is there anyway I can call gcd
without putting Fraction.
in front of it? In Java I would normally create a static method and then just call it. I could very easily put the GCD code inside of the init, but I am trying to learn here!
I am missing a lot here. Can anyone explain: static methods, helper methods in a class and pretty much how I can use various methods inside of a class?
class Fraction(object):
def __init__(self, a, b):
if Fraction.gcd(a, b) > 1:
d = Fraction.gcd(a, b)
self.num = a/d
self.denom = b/d
else:
self.num = a
self.denom = b
@staticmethod
def gcd(a,b):
if a > b: a,b = b,a
while True:
if b % a == 0: return a
a, b = b%a, a
def __repr__(self):
return str(self.num) + "/" + str(self.denom)
Don't forget, in Python not everything needs to be in a class. There's nothing about gcd
that makes it better-suited to being a class method than a standalone function: so take it out of the class. Now you can just call gcd(a, b)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With