Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use static/helper method in a class?

Tags:

python

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)
like image 267
mergesort Avatar asked Nov 29 '22 17:11

mergesort


1 Answers

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

like image 144
Daniel Roseman Avatar answered Dec 06 '22 19:12

Daniel Roseman